【问题标题】:Setting DisplayMemberPath of DataTemplate设置 DataTemplate 的 DisplayMemberPath
【发布时间】:2017-11-26 14:16:55
【问题描述】:

我有以下数据模板:

<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:我删除了不相关的代码部分,如样式、一些道具等,并尽可能地简化代码。

【问题讨论】:

  • 您不能在 XAML 中执行此操作。您需要为每列定义一个 DataTemplate。
  • @mm8。请写下来作为答案,以便我接受。

标签: c# .net wpf xaml data-binding


【解决方案1】:
<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>

【讨论】:

    【解决方案2】:

    您不能在 XAML 中执行此操作。您需要为每列定义一个DataTemplate

    没有办法只更改模板中绑定的路径并保留其余部分。模板必须作为一个整体来定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-07
      • 1970-01-01
      • 2011-03-08
      • 2016-02-06
      • 1970-01-01
      相关资源
      最近更新 更多