Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic DataTemplate used in multiple GridViewColumns

I have a GridView that displays some values:

<ListView ItemsSource="{Binding MyDataSource}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Date1" DisplayMemberBinding="{Binding Date1}" />
            <GridViewColumn Header="Date2" DisplayMemberBinding="{Binding Date2}" />
            ...other Columns, not necessarily containing dates...
        </GridView>
    </ListView.View>
</ListView>

This works fine. Now I want to create a data template that formats a date in a specific way:

<DataTemplate x:Key="MySpecialDate">
    <TextBlock Text="{Binding StringFormat={}{0:yyyy.MM.dd}}" />
</DataTemplate>

Adding CellTemplate won't work as long as DisplayMemberBinding is specified. Thus, I have to remove the DisplayMemberBinding attribute:

<GridViewColumn Header="Date1" CellTemplate="{StaticResource MySpecialDate}" />
<GridViewColumn Header="Date2" CellTemplate="{StaticResource MySpecialDate}" />

Here's the question: Now that DisplayMemberBinding is gone, how do I tell the GridView which property to display? GridViewColumn does not have a DataContext property.

Of course, I could put the name of the property (Date1 resp. Date2) into the DataTemplate, but then I would need one template for each property and that would defeat the whole purpose of having a template.

<!-- I don't want that -->
<DataTemplate x:Key="MySpecialDate1">
    <TextBlock Text="{Binding Date1, StringFormat={}{0:yyyy.MM.dd}}" />
</DataTemplate>
<DataTemplate x:Key="MySpecialDate2">
    <TextBlock Text="{Binding Date2, StringFormat={}{0:yyyy.MM.dd}}" />
</DataTemplate>
like image 376
Heinzi Avatar asked Nov 14 '22 13:11

Heinzi


1 Answers

Related to your question is mine: Pass multiple resources into a DataTemplate which I finally found a solution for. I think you cannot get around the definition of a template for every such date. But depending on the complexity of your display template this solution keeps the additional DataTemplates code to a minimum:

<DataTemplate x:Key="DateX">
  <ContentPresenter ContentTemplate="{StaticResource MySpecialDate}" local:YourClass.AttachedDate="DateX"/>
</DataTemplate>

These additional DataTemplates use an attached property which can then be used by a converter in the DataTemplate "MySpecialDate". The attached property has to be defined in the code behind. The answer to my own question contains a complete example.

like image 124
Pascal Avatar answered Nov 16 '22 03:11

Pascal