我有以下DataTemplate:
<Window.Resources>
<DataTemplate x:Key="MyDataGridCell_TextBox">
<TextBlock Text="{Binding}" />
</DataTemplate>
</Window.Resources>
我的DataGrid中的以下DataGridColumn:
<DataGrid ItemsSource="{Binding Logs}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="A" CellTemplate="{StaticResource MyDataGridCell_TextBox}
HOW_DO_I_SET_HERE_DisplayMember_To_PropA???"/>
<DataGridTemplateColumn Header="B" CellTemplate="{StaticResource MyDataGridCell_TextBox}
HOW_DO_I_SET_HERE_DisplayMember_To_PropB???"/>
</DataGrid.Columns>
</DataGrid>
如何从DataGridTemplateColumn设置DataTemplate的DisplayMemberPath?
public class Log
{
public string PropA {get;set;}
public string PropB {get;set;}
}
Logs <=> ObservableCollection<Log>
PS:我删除了不相关的代码部分,如样式,一些道具等,并试图尽可能地简化代码。
答案 0 :(得分:0)
<Window.Resources>
<DataTemplate x:Key="MyDataGridCell_TextBoxA">
<TextBlock Text="{Binding PropA}" />
</DataTemplate>
<DataTemplate x:Key="MyDataGridCell_TextBoxB">
<TextBlock Text="{Binding PropB}" />
</DataTemplate>
</Window.Resources>
如上所述定义2个模板,然后使用模板选择器
public class CellTextTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
ContentPresenter presenter = container as ContentPresenter;
DataGridCell cell = presenter.Parent as DataGridCell;
DataGridTemplateColumn it = cell.Column as DataGridTemplateColumn;
if (it.Header == A)
{
//return logic depends on where you are adding this class
}
else
{
//return logic depends on where you are adding this class
}
}
}
然后添加您的资源:
<Window.Resources>
<mypath:CellTextTemplateSelector x:Key = "mySelector"/>
...
</Window.Resources>
最后
<DataGrid ItemsSource="{Binding Logs}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="A" CellTemplateSelector="{StaticResource mySelector}"/>
<DataGridTemplateColumn Header="B" CellTemplateSelector="{StaticResource mySelector}"/>
</DataGrid.Columns>
</DataGrid>