在 WPF DataGrid 中合并单元格 [英] Merge Cells in WPF DataGrid
本文介绍了在 WPF DataGrid 中合并单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个跨越一列中多行的 WPF 数据网格.像这样:
I want to create a WPF datagrid that spans over multiple rows in one column. Like this:
+-------+----------------+
| Name | Attributes |
+-------+----------------+
| | Horse Power |
| BMW +----------------+
| | Color |
+-------+----------------+
| | Weight |
| Ford +----------------+
| | Color |
+-------+----------------+
如何更改以下代码以完成它?
How can the following code be changed to get it done?
<DataGrid AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" />
<DataGridTextColumn Header="Attributes" />
</DataGrid.Columns>
</DataGrid>
推荐答案
尝试使用 DataGridTemplateColumn
.我为数据绑定创建了示例测试类
Try use DataGridTemplateColumn
. I created sample test class for databinding
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 中的数据网格
And a datagrid in 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;
这篇关于在 WPF DataGrid 中合并单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文