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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With