The behavior I am aiming for is: I have a data grid with a single column. It is bound to a list of items which contain various information about a person. When not selected, the row simply displays the person's name. When the row is selected (i.e. clicked on), I was to show more information about the person.
My first attempt was to use a DataGridTemplateColumn where the CellTemplate is a ContentControl. The style of the ContentControl is determined by the status of the selected row.
My style:
<DataTemplate x:Key="NotSelectedTemplate">
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContentControl}, Path=DataContext.PatientName.FormattedName, Mode=OneWay, BindsDirectlyToSource=True, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
<DataTemplate x:Key="SelectedTemplate">
<TextBlock Height="60" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContentControl}, Path=DataContext.PatientName.FormattedName, Mode=OneWay, BindsDirectlyToSource=True, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
<Style x:Key="SelectableContentStyle" TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=IsSelected}" Value="False">
<Setter Property="ContentTemplate" Value="{StaticResource NotSelectedTemplate}" />
</DataTrigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=IsSelected}" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
My datagrid columns:
<DataGrid.Columns>
<DataGridTemplateColumn Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ContentControl Style="{StaticResource SelectableContentStyle}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
This approach works, however the binding in each DataTemplate is pretty ugly. I am relatively inexperienced at WPF, so I'm sure there must be a much better way to implement this.
Basically, 1) Is there a better way to acheive this behavior? 2) Is there a better way to bind to the DataTemplate so I am not chasing RelativeSources any time I want to access a property?