I have a ListView in a WPF window containing a number of GridViewColumns. The first column is used for a checkbox. The remainder of the columns are very similar, containing a datatemplate with a textblock. I would like to be able to reuse a single datatemplate for each of these, but I’m not sure how to pull this off, since the binding is different for each column.
Below is some example XAML. The first GridViewColumn is the checkbox. The other two contain examples of the DataTemplate. How can I reuse this DataTemplate across several columns that have different bindings?
<ListView
AlternationCount="2"
DataContext="{StaticResource TaskGroups}"
ItemContainerStyle="{StaticResource TaskItemStyle}"
ItemsSource="{Binding}"
SelectionMode="Single">
<ListView.View>
<GridView>
<GridViewColumn
Header="Completed"
CellTemplate="{StaticResource CompletedCellTemplate}"
/>
<GridViewColumn Header="Name">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<Rectangle Name="StrikeThrough" HorizontalAlignment="Stretch" VerticalAlignment="Center"
Height="1" StrokeThickness="1" Stroke="Transparent"/>
<TextBlock Text="{Binding Path=Name}"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=IsCompleted}" Value="True">
<Setter TargetName="StrikeThrough" Property="Stroke" Value="Black"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Status">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<Rectangle Name="StrikeThrough" HorizontalAlignment="Stretch" VerticalAlignment="Center"
Height="1" StrokeThickness="1" Stroke="Transparent"/>
<TextBlock Text="{Binding Path=StatusDescription}"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=IsCompleted}" Value="True">
<Setter TargetName="StrikeThrough" Property="Stroke" Value="Black"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
The only difference in those templates is the text which is displayed. So, you can create user control to reuse layout and strikethrough logic.
Moreover, there is
TextBlock.TextDecoration. It’s better to use that instead of custom tricks.Here is the example of mentioned control:
MyUserControl.xaml:
MyUserControl.xaml.cs:
And converter: