我有一个二维的对象数组,我基本上想要将每个对象数据绑定到WPF网格中的单元格.目前我有这个工作,但我在程序上做了大部分工作.我创建了正确数量的行和列定义,然后循环遍历单元格并创建控件并为每个控件设置正确的绑定.
至少我希望能够使用模板来指定xaml中的控件和绑定.理想情况下,我想摆脱程序代码,并使用数据绑定完成所有操作,但我不确定这是否可能.
这是我目前使用的代码:
public void BindGrid()
{
m_Grid.Children.Clear();
m_Grid.ColumnDefinitions.Clear();
m_Grid.RowDefinitions.Clear();
for (int x = 0; x < MefGrid.Width; x++)
{
m_Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star), });
}
for (int y = 0; y < MefGrid.Height; y++)
{
m_Grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star), });
}
for (int x = 0; x < MefGrid.Width; x++)
{
for (int y = 0; y < MefGrid.Height; y++)
{
Cell cell = (Cell)MefGrid[x, y];
SolidColorBrush brush = new SolidColorBrush(); …Run Code Online (Sandbox Code Playgroud) 我有一个我希望绑定到WPF网格的集合.
我面临的问题是列数是动态的,并且依赖于集合.这是一个简单的模拟:
public interface IRows
{
string Message{get;}
IColumns[] Columns{get;}
}
public interface IColumns
{
string Header {get;}
AcknowledgementState AcknowledgementState{get;}
}
public interface IViewModel
{
ObservableCollection<IRows> Rows {get;}
}
Run Code Online (Sandbox Code Playgroud)
我希望我的视图绑定到Rows集合,该集合包含一组Columns.
My Columns集合包含一个应由图像表示的枚举(3种可能性中的1种).它还包含一个Message属性,该属性只能显示在一列中(静态且只是一些文本信息).它还包含一个Header字符串,该字符串应显示为该列的标题.

请注意,列数是可变的(在标题设置为Acknowledge的时刻,但这将更改为表示动态数据).
更新:这是在实施Rachel的建议之后
<ItemsControl
ItemsSource="{Binding Items, Converter={StaticResource PresentationConverter}}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid ShowGridLines="true"
local:GridHelpers.RowCount="{Binding RowCount}"
local:GridHelpers.ColumnCount="{Binding ColumnCount}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Row" Value="{Binding RowIndex}"/>
<Setter Property="Grid.Column" Value="{Binding ColumnIndex}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl Content="{Binding}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type UI:MessageEntity}">
<TextBox Text="{Binding Message}"></TextBox>
</DataTemplate>
<DataTemplate DataType="{x:Type UI:StateEntity}">
<TextBox Text="{Binding State}"></TextBox> …Run Code Online (Sandbox Code Playgroud)