您可以使用 Grid 作为ItemsPanel
ItemsControl 的,并将ItemsSource
属性绑定到您的 ObservableCollection。
假设您的单元格类如下所示:
public class Cell
{
public int Column { get; set; }
public int ColumnSpan { get; set; }
public int Row { get; set; }
public int RowSpan { get; set; }
public string Text { get; set; }
}
XAML 可以写成如下所示:
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<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 Column}"/>
<Setter Property="Grid.ColumnSpan" Value="{Binding ColumnSpan}"/>
<Setter Property="Grid.Row" Value="{Binding Row}"/>
<Setter Property="Grid.RowSpan" Value="{Binding RowSpan}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Text}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
以下代码将初始化 ItemsControl 的两个单元格:
public MainWindow()
{
InitializeComponent();
var cells = new ObservableCollection<Cell>();
cells.Add(new Cell { Column = 0, Row = 0, ColumnSpan = 1, RowSpan = 1, Text = "Cell 1" });
cells.Add(new Cell { Column = 2, Row = 2, ColumnSpan = 2, RowSpan = 1, Text = "Cell 2" });
DataContext = cells;
}