尝试使用DataGridTemplateColumn
。我为数据绑定创建了一个示例测试类。
public class Test
{
public Test(string name, string attribute1, string attribute2)
{
Name = name;
Attributes = new Attribute(attribute1, attribute2);
}
public string Name { get; set; }
public Attribute Attributes { get; set; }
}
public class Attribute
{
public Attribute(string attribute1, string attribute2)
{
Attribute1 = attribute1;
Attribute2 = attribute2;
}
public string Attribute1 { get; set; }
public string Attribute2 { get; set; }
}
在 XAML 中使用数据网格
<DataGrid AutoGenerateColumns="False" Name="dataGrid1" ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Name" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=Name}" VerticalAlignment="Center" Margin="3,3,3,3"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Attributes" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50*"/>
<RowDefinition />
<RowDefinition Height="50*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Path=Attributes.Attribute1}" VerticalAlignment="Center" Margin="3,3,3,3"/>
<Line Grid.Row="1" Stroke="Black" Stretch="Fill" X2="1" VerticalAlignment="Center"/>
<TextBlock Grid.Row="2" Text="{Binding Path=Attributes.Attribute2}" VerticalAlignment="Center" Margin="3,3,3,3"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
然后在代码后端填写它
List<Test> list = new List<Test>();
//populate list with your data here
dataGrid1.DataContext = list;
DataGrid
的原因是什么?这看起来足够简单,你应该可以更容易地在ListView
中完成,并使用自定义的 ListViewItems。 - GjeltemaListView
的最大粉丝,但对于您正在寻找的自定义功能,我认为它是更可取的选择。我发现DataGrid
(即使是第三方DataGrid
控件)也不能轻松地执行诸如“多行列单元格”之类的操作。 - Gjeltema