6

在 WPF DataGrid 的各个单元格上将字体设置为删除线样式的最佳(简单)方法是什么?

...

我知道的选项是在单个单元格中插入 TextBlock 控件或使用 DataGridTemplateColumn - 并在其中使用 TextDecorations 属性。无论哪种方式,这都是一项艰巨的任务,我想使用 DataGrid 的默认 AutoGenerate Columns 功能,特别是因为我的 ItemsSource 是一个 DataTable。

顺便说一句,有没有办法访问使用默认 DataGridTextColumn 生成的 TextBlock?

4

2 回答 2

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

当然,您可以将 setter 包装在 DataTrigger 中以有选择地使用它。

于 2011-04-20T14:12:40.520 回答
0

如果要根据特定单元格绑定删除线,则会遇到绑定问题,因为 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();
    }
  }
于 2013-11-17T13:37:42.707 回答