我想将每个单元格中的文本和工具提示绑定到对象的属性。 网格看起来像这样(只绑定文本):
<DataGrid x:Name="myGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Prop1" Binding="{Binding Prop1.Text}" />
<DataGridTextColumn Header="Prop2" Binding="{Binding Prop2.Text}" />
<DataGridTextColumn Header="Prop3" Binding="{Binding Prop3.Text}" />
</DataGrid.Columns>
</DataGrid>
我的数据如下:
public class TableModel
{
public List<RowModel> Rows = new List<RowModel>();
}
public class RowModel
{
public CellModel Prop1 { get; set; }
public CellModel Prop2 { get; set; }
public CellModel Prop3 { get; set; }
}
public class CellModel
{
public string Text { get; set; }
public string ToolTip { get; set; }
}
Initilialization:
TableModel t = new TableModel();
t.Rows.Add(new RowModel
{
Prop1 = new CellModel { Text = "text1", ToolTip = "this is text 1" },
Prop2 = new CellModel { Text = "text2", ToolTip = "this is text 2" },
Prop3 = new CellModel { Text = "text3", ToolTip = "this is text 3" }
});
t.Rows.Add(new RowModel
{
Prop1 = new CellModel { Text = "cell 2.1", ToolTip = "this is another text 1" },
Prop2 = new CellModel { Text = "cell 2.2", ToolTip = "this is another text 2" },
Prop3 = new CellModel { Text = "cell 2.3", ToolTip = "this is another text 3" }
});
为了绑定工具提示,我认为类似于以下内容是可能的:
<DataGrid x:Name="myGrid" AutoGenerateColumns="False">
<DataGrid.Resources>
<DataTemplate x:Key="cellTemplate">
<TextBlock Text="{Binding Prop1.Text}" ToolTip="{Binding Prop1.ToolTip}" />
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Prop1" CellTemplate="{StaticResource cellTemplate}" />
<DataGridTemplateColumn Header="Prop2" CellTemplate="{StaticResource cellTemplate}" />
<DataGridTemplateColumn Header="Prop3" CellTemplate="{StaticResource cellTemplate}" />
</DataGrid.Columns>
</DataGrid>
但上面的代码将所有列绑定到Prop1。
可以以某种方式更改,以便绑定正常工作吗?
(注意:我实际上是动态生成我的列,只有3个,我真的只想使用一个模板)。
非常感谢任何帮助。