按单元格定义填充矩阵



我需要在类似矩阵的视图中显示和编辑我的数据。所有数据将收集在ObserverableCollection中。然后我将按照单元格定义填充集合。每个单元格定义都有其行和列的键,以及一个字符串,该字符串应显示在矩阵中。

public class CellViewModel : ViewModelBase
{
public object RowKey { get; set; }    
public object ColumnKey { get; set; }
public string CellText { get; set; }
}

这意味着,当CellViewModel被添加到集合中,并且已经存在具有相同RowKey的行时,该单元格将被填充到该行的适当列中。如果该列不存在,将添加一个新列。关键可以是任何对象,有了这个人就可以用任何对象关键添加一个单元格,而不需要关心设置单元格的正确位置。例如,我用CellViewModels:填充集合

GridCellViewModelCollection = new ObservableCollection<CellViewModel>
{
new CellViewModel
{
RowKey = 1,
ColumnKey = 1,
CellText = "Cell1_1"
},
new CellViewModel
{
RowKey = "string",
ColumnKey = 'char',
CellText = "Cell2_2"
},
new CellViewModel
{
RowKey = 3,
ColumnKey = 1,
CellText = "Cell3_1"
},
new CellViewModel
{
RowKey = 1,
ColumnKey = 3,
CellText = "Cell1_3"
},
new CellViewModel
{
RowKey = 3,
ColumnKey = 'char',
CellText = "Cell3_2"
}
}

那么矩阵应该是这样的:

column1 column2 column3
row1    Cell1_1         Cell1_3
row2            Cell2_2
row3    Cell3_1 Cell3_2

我尝试过使用ItemsControl,并将整个集合转换为适合带占位符的ItemsControl。。。

var list = new List<CellViewModel>{ null, null, cellViewModel };

但我认为这不是一个好主意。并且位置持有者不会保留保持整个矩阵有序的位置。此外,ItemsControl没有行和列的标题。

有什么想法或建议吗?我应该用哪种控制来做这件事?

您可以在ItemsControl中使用Grid作为ItemsPanel,并在ItemContainerStyle中的Style中绑定Grid.ColumnGrid.Row属性。当然,列和行索引是从零开始的。

<ItemsControl ItemsSource="{Binding GridCellViewModelCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid IsItemsHost="True">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Grid.Column" Value="{Binding ColumnKey}"/>
<Setter Property="Grid.Row" Value="{Binding RowKey}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding CellText}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

最新更新