Best way to set strikethrough in individual WPF DataGrid cells?

What is the best (easiest) way to set strikethrough style fonts to individual WPF DataGrid cells?

...

The options that I know of are pasting TextBlock controls into separate cells or using the DataGridTemplateColumn - and using the TextDecorations property in it. In any case, this is quite a mission, I would like to use the default AutoGenerate Columns function for a DataGrid, especially since my ItemSource is a DataTable.

As an aside, is there a way to access the TextBlock generated using the default DataGridTextColumn?

+6
source share
2 answers
<DataGridTextColumn Binding="{Binding Name}"> <DataGridTextColumn.ElementStyle> <Style TargetType="{x:Type TextBlock}"> <Setter Property="TextDecorations" Value="Strikethrough"/> </Style> </DataGridTextColumn.ElementStyle> </DataGridTextColumn> 

Of course, you can wrap the setter in a DataTrigger to use it selectively.

+6
source

If you want to bind strikethrough based on a specific cell, you have a bind problem because DataGridTextColumn.Binding only modifies the contents of TextBox.Text. If the value of the Text property is all you need, you can bind to the TextBox itself:

 <Setter Property="TextDecorations" Value="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource TextToTextDecorationsConverter}}" /> 

But if you want to bind to something other than TextBox.Text, you need to bind through DataGridRow, which is the parent of the TextBox in the visual tree. The DataGridRow has an Item property that gives access to the full object used for the entire row.

 <Setter Property="TextDecorations" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path =Item.SomeProperty, Converter={StaticResource SomePropertyToTextDecorationsConverter}}" /> 

The converter looks like this: it is assumed that something is of type boolean:

 public class SomePropertyToTextDecorationsConverter: IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool) { if ((bool)value) { TextDecorationCollection redStrikthroughTextDecoration = TextDecorations.Strikethrough.CloneCurrentValue(); redStrikthroughTextDecoration[0].Pen = new Pen {Brush=Brushes.Red, Thickness = 3 }; return redStrikthroughTextDecoration; } } return new TextDecorationCollection(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } 
0
source

Source: https://habr.com/ru/post/886313/


All Articles