5

I have a WPF WrapPanel, it contains some of Buttons, I want to re arrange them at runtime. The XAML code at design time like:

<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>

But, I want to re arrange the Buttons at run time. Can you help me about that.

Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
Abdullah Zaid
  • 171
  • 3
  • 9

2 Answers2

3

You can do something like this:

    <ItemsControl ItemsSource="{Binding Items}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding}" Width="75"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

Items would be a property on your DataContext and would typically be an ObservableCollection of some sort. In the simplest case, it could be a collection of strings that correspond to the button captions. When you rearrange the ObservableCollection elements, it will rearrange the corresponding buttons in the ItemsControl, using a WrapPanel to arrange them.


On a side note, using this type of approach is a step toward what is known as the MVVM pattern (Model-View-ViewModel.) This is quickly becoming the industry standard pattern for developing WPF applications and has a lot of advantages when it comes to creating flexible, dynamic UIs. I highly recommend researching this pattern if you want to do any significant WPF development. It takes a bit of time to get used to, but it's ultimately quite worthwhile.

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
0

If you want to rearrange the children at run time, you have two options, creating (or at least manipulating) the children of the WrapPannel in code instead of XAML, or setting up Triggers (in a Style tag) to manipulate the buttons as needed.

Here's an example.

Community
  • 1
  • 1
Christopher Stevenson
  • 2,843
  • 20
  • 25