我有一个 WPF WrapPanel
,它包含一些 Buttons
,我想在运行时重新排列它们。设计时的 XAML 代码如下:
<Grid x:Name="LayoutRoot">
<WrapPanel Margin="133,127,216,189" Background="#FF979797">
<Button Content="Button" Width="75"/>
<Button Content="Button" Width="75"/>
<Button Content="Button" Width="75"/>
<Button Content="Button" Width="75"/>
<Button Content="Button" Width="75"/>
<Button Content="Button" Width="75"/>
</WrapPanel>
</Grid>
但是,我想在运行时重新排列 Buttons
。你能帮我一下吗?
最佳答案
你可以这样做:
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" Width="75"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Items 将是您的 DataContext 上的一个属性,通常是某种 ObservableCollection。在最简单的情况下,它可以是与按钮标题相对应的字符串集合。当您重新排列 ObservableCollection 元素时,它会重新排列 ItemsControl 中的相应按钮,使用 WrapPanel 来排列它们。
附带说明一下,使用这种方法是朝着所谓的 MVVM 模式(模型- View - View 模型)迈出的一步。这种模式正在迅速成为开发 WPF 应用程序的行业标准模式,并且具有很多优势在创建灵活、动态的 UI 时。如果您想进行任何重要的 WPF 开发,我强烈建议您研究这种模式。这需要一些时间来适应,但最终是非常值得的。
关于c# - 在运行时重新排列 WrapPanel 中的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17552474/