Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re arranging controls in WrapPanel at runtime

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.

like image 535
Abdullah Zaid Avatar asked Oct 22 '22 06:10

Abdullah Zaid


1 Answers

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.

like image 119
Dan Bryant Avatar answered Oct 24 '22 04:10

Dan Bryant