Goran
Goran

Reputation: 6518

Specifying data context for DataGridTemplateColumn

DataGrid is bound to List, where T has several nested properties (amongst others).

class T
{
    public X PropertyX {get;}
    public Y PropertyY {get;}
    public Z PropertyZ {get;}
}

class X { public A SomeProperty {get;}}
class Y { public A SomeProperty {get;}}
class Z { public A SomeProperty {get;}}

X, Y and Z classes have the same property SomeProperty of type A.

I need to show data for SomeProperty of PropertyX, PropertyY and PropertyZ, respectively.

So, I need something like this:

<DataGridTemplateColumn DataContext="{Binding X.A}" CellTemplate="{StaticResource CommonTemplate}" />
<DataGridTemplateColumn DataContext="{Binding Y.A}" CellTemplate="{StaticResource CommonTemplate}" />
<DataGridTemplateColumn DataContext="{Binding Z.A}" CellTemplate="{StaticResource CommonTemplate}" />

Obviously DataGridTemplate column does not have DataContext, so I am wondering is this possible to do? CommonTemplate is quite large, and I would like to reuse it.

Any ideas?

Upvotes: 0

Views: 289

Answers (1)

ASh
ASh

Reputation: 35680

you can reuse existing DataTemplate in another DataTemplate, which also specifies DataContext:

<DataGridTemplateColumn Header="x">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding PropertyX.SomeProperty}" 
                              ContentTemplate="{StaticResource CellTemplate}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

<DataGridTemplateColumn Header="y">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding PropertyY.SomeProperty}" 
                              ContentTemplate="{StaticResource CellTemplate}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Upvotes: 1

Related Questions