【问题标题】:Re arranging controls in WrapPanel at runtime在运行时重新排列 WrapPanel 中的控件
【发布时间】:2013-07-09 15:40:32
【问题描述】:

我有一个 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。你能帮我解决这个问题吗?

【问题讨论】:

    标签: c# wpf xaml button wrappanel


    【解决方案1】:

    你可以这样做:

        <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 开发,我强烈建议您研究这种模式。这需要一点时间来适应,但最终还是很值得的。

    【讨论】:

      【解决方案2】:

      如果您想在运行时重新排列子项,您有两个选择,在代码而不是 XAML 中创建(或至少操作)WrapPannel 的子项,或setting up Triggers(在 Style 标记中)来操作按钮。

      Here's 一个例子。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        • 2011-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多