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>
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 DataTemplate
s code to a minimum:
<DataTemplate x:Key="DateX">
<ContentPresenter ContentTemplate="{StaticResource MySpecialDate}" local:YourClass.AttachedDate="DateX"/>
</DataTemplate>
These additional DataTemplate
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With