1

我想根据它的值更改单元格内容文本的字体和颜色,但我需要从代码中添加列。问题是表格显示了十六进制值,而不是对单元格值进行着色。

我在 XAML 资源中添加了:

<Style x:Key="MyStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="{Binding TextColor}" />
</Style>

以下代码行初始化列:

DataGridTextColumn column = new DataGridTextColumn();
                        column.Header = field.name;
                        column.Binding = new Binding(field.name)
                        {
                            Mode = BindingMode.TwoWay,
                            UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                            Converter = new NameToBrushConverter()
                        };
                        column.ElementStyle = this.FindResource("MyStyle") as Style;
                        dgwDataMain.Columns.Add(column);

我的自定义功能:

public class NameToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return ((string)value == "asd") ? Brushes.Red : Brushes.Black;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Binding.DoNothing;
        }
    }
4

1 回答 1

2

您可以使用MultiValueConverter.

例子:

DataGridTextColumn column = new DataGridTextColumn();
column.Header = "Name";
column.Binding = new Binding("Name")
{
      Mode = BindingMode.TwoWay,
      UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged                
};
column.ElementStyle = this.FindResource("MyStyle") as Style;
grid.Columns.Add(column);

List<Foo> _source = new List<Foo> 
{
        new Foo{ Name ="test1"},
        new Foo{ Name ="test2"},
        new Foo{ Name ="test3"}
};

grid.ItemsSource = _source;

富类:

class Foo
{
   public string Name { get; set; }       
}

样式 XAML:

<local:NameToBrushConverter x:Key="nameToBC" />

<Style x:Key="MyStyle" TargetType="{x:Type TextBlock}">
   <Setter Property="Foreground" >
            <Setter.Value>
                 <MultiBinding Converter="{StaticResource nameToBC}" >                       
                       <Binding Path="." />                      
                 </MultiBinding>
             </Setter.Value>
    </Setter>
</Style>

多值转换器代码:

 class NameToBrushConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            Foo item = values[0] as Foo;
            if (item != null)
            {               
                if (item.Name == "test2")
                    return Brushes.Red;
                else
                    return Brushes.Black;
            }

            return Brushes.Black;
        }
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
于 2013-01-16T16:36:51.983 回答