如果要根据特定单元格绑定删除线,则会遇到绑定问题,因为 DataGridTextColumn.Binding 仅更改 TextBox.Text 的内容。如果您只需要 Text 属性的值,则可以绑定到 TextBox 本身:
<Setter Property="TextDecorations"
Value="{Binding RelativeSource={RelativeSource Self},
Path=Text,
Converter={StaticResource TextToTextDecorationsConverter}}" />
但是,如果要绑定到不同于 TextBox.Text 的内容,则必须通过 DataGridRow 进行绑定,它是可视树中 TextBox 的父级。DataGridRow 有一个 Item 属性,它允许访问用于整行的完整对象。
<Setter Property="TextDecorations"
Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}},
Path =Item.SomeProperty,
Converter={StaticResource SomePropertyToTextDecorationsConverter}}" />
转换器看起来像这样,假设某些东西是布尔类型:
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();
}
}