c# – 在运行时重新安排WrapPanel中的控件
发布时间:2020-12-15 05:40:27 所属栏目:百科 来源:网络整理
导读:我有一个 WPF WrapPanel,它包含一些按钮,我想在运行时重新安排它们.设计时的XAML代码如: Grid x:Name="LayoutRoot" WrapPanel Margin="133,127,216,189" Background="#FF979797" Button Content="Button" Width="75"/ Button Content="Button" Width="75"/
我有一个
WPF WrapPanel,它包含一些按钮,我想在运行时重新安排它们.设计时的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> 但是,我想在运行时重新安排按钮.你能帮帮我吗? 解决方法
你可以这样做:
<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模式(Model-View-ViewModel)的一步.这很快成为开发WPF应用程序的行业标准模式,并且在它到来时具有很多优势.创建灵活的动态UI.如果您想进行任何重要的WPF开发,我强烈建议您研究这种模式.需要一点时间来习惯,但最终还是值得的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |