I am writing a WPF program in C# in which I have a ListView for which the columns will be populated at runtime. I would like to use a custom DataTemplate for the GridViewColumn objects in the ListView.
In the examples I have seen where the number of columns is fixed in advance, a custom DataTemplate is often created using something like the XAML below.
<DataTemplate x:Key="someKey">
<TextBlock Text="{Binding Path=FirstName}" />
</DataTemplate>
This DataTemplate could also later be assigned to GridViewColumn.CellTemplate in the code-behind by calling FindResource(“someKey”). However, this alone is of no use to me, because in this example the Path element is fixed to FirstName. Really I need something where I can set the Path in code.
It is my impression that something along these lines may be possible if XamlReader is used, but I’m not sure how in practice I would do this. Any solutions are greatly appreciated.
It is easy to build what you need using two DataTemplates working in concert: The outer DataTemplate simply sets the DataContext for the inner DataTemplate, as follows:
The only tricky thing is making it convenient to set this on a GridViewColumn. I would accomplish this with attached properties, allowing you to write:
Or equivalently in code:
Either of these would cause the DataTemplate named “DisplayTemplate” to be used to display the FirstName in the column.
The helper class would be implemented as:
How it works: Whenever the properties are both set, a new DataTemplate is constructed and the GridViewColumn.CellTemplate property is updated.