C# 设置DataTemplate的DisplayMemberPath
我有以下数据模板:C# 设置DataTemplate的DisplayMemberPath,c#,.net,wpf,xaml,data-binding,C#,.net,Wpf,Xaml,Data Binding,我有以下数据模板: <Window.Resources> <DataTemplate x:Key="MyDataGridCell_TextBox"> <TextBlock Text="{Binding}" /> </DataTemplate> </Window.Resources> 以及我的DataGrid中的以下DataGrid列: <DataGrid ItemsSource="{Binding
<Window.Resources>
<DataTemplate x:Key="MyDataGridCell_TextBox">
<TextBlock Text="{Binding}" />
</DataTemplate>
</Window.Resources>
以及我的DataGrid中的以下DataGrid列:
<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:我删除了不相关的代码部分,如样式、一些道具等,并尽可能简化代码
<Window.Resources>
<DataTemplate x:Key="MyDataGridCell_TextBoxA">
<TextBlock Text="{Binding PropA}" />
</DataTemplate>
<DataTemplate x:Key="MyDataGridCell_TextBoxB">
<TextBlock Text="{Binding PropB}" />
</DataTemplate>
</Window.Resources>
然后添加您的资源:
<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>
在XAML中不能这样做。您需要为每列定义一个DataTemplate
无法仅更改模板中绑定的路径而保留其余的路径。模板必须定义为一个整体。在XAML中不能这样做。您需要为每列定义一个数据模板。@mm8。请写下来作为答案,这样我就可以接受了。
<DataGrid ItemsSource="{Binding Logs}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="A" CellTemplateSelector="{StaticResource mySelector}"/>
<DataGridTemplateColumn Header="B" CellTemplateSelector="{StaticResource mySelector}"/>
</DataGrid.Columns>
</DataGrid>