问题
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>
回答1:
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.
回答2:
If the format is really that widely used, then you could use the following
In DateTimeColumn.cs
public class DateTimeColumn : GridViewColumn
{
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (Equals(e.PropertyName, "DisplayMemberBinding") && DisplayMemberBinding != null)
{
DisplayMemberBinding.StringFormat = "{0:yyyy.MM.dd}";
}
}
}
XAML code...
<local:DateTimeColumn DisplayMemberBinding="{Binding Date1}" />
(I don't like the format as a magic string, but the code can be modified as needed.)
来源:https://stackoverflow.com/questions/8328443/generic-datatemplate-used-in-multiple-gridviewcolumns