WPF: How to create a custom items control panel?

删除回忆录丶 提交于 2019-12-05 10:35:32

A useful strategy to solve this kind of problem is to manipulate the source data into a format more suitable for consumption by an ItemsControl. For example, a two-dimensional array of items, or a linear collection of items that contain their own two-dimensional coordinates, is hard to utilize.

Instead, with a simple data structure transformation you can bind your ItemsSource to collection of collections. The outer collection contains three rows and each inner collection contains four items. Each item can contain its actual row and column coordinates and can handle whether the corresponding cell should display any data.

Here's a 2x2 example to show you what I mean:

<Grid>
    <Grid.Resources>
        <coll:ArrayList x:Key="sampleData">
            <x:Array Type="sys:String">
                <sys:String>1</sys:String><sys:String>2</sys:String>
            </x:Array>
            <x:Array Type="sys:String">
                <sys:String>3</sys:String<sys:String>4</sys:String>
            </x:Array>
        </coll:ArrayList>
    </Grid.Resources>
    <ItemsControl ItemsSource="{StaticResource sampleData}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal"/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Border BorderBrush="Black" BorderThickness="1" Width="50" Height="50">
                                <TextBlock Text="{Binding}"/>
                            </Border>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

which produces:

+---+---+
| 1 | 2 |
+---+---+
| 3 | 4 |
+---+---+
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!