c# - 在运行时重新排列 WrapPanel 中的控件

标签 c# wpf xaml button wrappanel

我有一个 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/

相关文章:

c# - 在 C# 中使用 RegEx 验证 float

c# - 绑定(bind)到 ItemsControl 中 ItemsControl 的 AlternationIndex

c# - Entity Framework LINQ 复杂查询 - 组合多个谓词

c# - 时间跨度数据类型 C#

非焦点形式的 C#/WPF 热键(如 launchy)

c# - 如何在 ScrollViewer 中滚动水平 StackPanel?

xaml - "m2"在 XAML 中意味着什么?

c# - 命名空间中不存在控件

c# - 拆分字符串并验证每个部分

c# - 如何在运行时使用资源字典更改 UI 语言?