WPF:如何创建自定义项控制面板?

Bor*_*ris 5 wpf custom-controls itemscontrol

我想设计一个自定义项目控制面板ListBox.有3个要求:

  1. 它应该具有属性int rows,int columns并且将定义由面板构成的单元矩阵.这就是面板应该是什么样子(颜色是无关紧要的,我只想表明该面板由3x4矩阵中的12个空单元组成): 替代文字

  2. 如果项目控件中的项目数小于已定义单元格的数量,则应绘制所有单元格.例如,如果图片中显示的3x4矩阵中只放置了4个项目,则应绘制所有单元格,其中只有4个应包含项目.

  3. 应该可以通过一些数据绑定来设置哪个单元将托管哪个项目.例如,假设我有一份人员名单.这份名单包含类型的项目PersonPerson类包含两个属性XY.我应该能够将数据绑定Xrow细胞,并Ycolumn细胞外,从而使自己设定的哪个单元面板将包含从列表中哪个人.

如果创建项目控制面板没有意义,请建议什么是更好的方法.说实话,我很困惑如何开始这个.谢谢你的帮助.干杯!

Ric*_*key 1

解决此类问题的一个有用策略是将源数据处理为更适合ItemsControl. 例如,项目的二维数组或包含其自己的二维坐标的项目的线性集合很难利用。

相反,通过简单的数据结构转换,您可以将您的集合绑定ItemsSource到集合的集合。外部集合包含三行,每个内部集合包含四个项目。每个项目都可以包含其实际的行和列坐标,并且可以处理相应的单元格是否应显示任何数据。

这是一个 2x2 的示例来向您展示我的意思:

<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>
Run Code Online (Sandbox Code Playgroud)

其产生:

+---+---+
| 1 | 2 |
+---+---+
| 3 | 4 |
+---+---+
Run Code Online (Sandbox Code Playgroud)