0

I have the following DataTemplate:

<Window.Resources>
    <DataTemplate x:Key="MyDataGridCell_TextBox">
        <TextBlock Text="{Binding}" />
    </DataTemplate>
</Window.Resources>

And the following DataGridColumn in my 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>

How can I set the DisplayMemberPath of the DataTemplate from DataGridTemplateColumn?

public class Log
{
    public string PropA {get;set;}
    public string PropB {get;set;}
}

Logs <=> ObservableCollection<Log>

PS: I removed the irrelevant code parts like styles, some props etc. and tried to simplify the code as much as I could.

A.B.
  • 2,374
  • 3
  • 24
  • 40

2 Answers2

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>

Define 2 template like above, then use a template selector

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
        }

    }
}

Then add in your resources:

<Window.Resources>
    <mypath:CellTextTemplateSelector x:Key = "mySelector"/>
    ...
</Window.Resources>

and finally

<DataGrid ItemsSource="{Binding Logs}">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="A" CellTemplateSelector="{StaticResource mySelector}"/> 
        <DataGridTemplateColumn Header="B" CellTemplateSelector="{StaticResource mySelector}"/> 
    </DataGrid.Columns>
</DataGrid>
Daniele Sartori
  • 1,674
  • 22
  • 38
0

You can't do this in XAML. You need to define a DataTemplate per column.

There is no way to just change the path of a binding in a template and keep the rest. A template must be defined as a whole.

mm8
  • 163,881
  • 10
  • 57
  • 88