在代码中动态添加IValueConverter

时间:2012-08-24 12:08:07

标签: c# .net wpf

我正在使用.NET 3.5

我有一个DataGridTextColumn,我想在该列的值为false时将背景颜色变为红色。我已经在XMAL中看到了这一点,但无法弄清楚如何在代码中执行此操作

DataGridTextColumn column = new DataGridTextColumn() { Header = "Can Connect", Binding = new Binding("CanConnect") };
//How to add the converter here so that the background of the cell turns red when CanConnect = false?

    public class IsConnectedConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool input = (bool)value;
            switch (input)
            {
                case true:
                    return DependencyProperty.UnsetValue;
                default:
                    return Brushes.Red;
            }
        }
    }

4 个答案:

答案 0 :(得分:5)

使用Binding课程的Converter property

new Binding("CanConnect") {
    Converter = new IsConnectedConverter()
}

在您的代码中,您将绑定分配给Binding的{​​{1}}属性,但该属性仅控制单元格的内容。对于单元格的视觉外观,您将需要一个样式,也可以在代码隐藏中设置:

DataGridTextColumn

在该代码中,Style st = new Style(typeof(DataGridCell)); st.Setters.Add(new Setter(Control.BackgroundProperty, binding)); column.CellStyle = st; 将是一个带有新binding对象的变量(或者上面的构造函数和初始化调用)。正如docs on DataGridTextColumn.CellStyle所描述的,样式的目标类型必须是Binding,并且该类继承自DataGridCell,我们可以为Control的依赖属性添加setter,例如Control

我恐怕现在无法测试此代码;我希望它能让你了解如何继续。

答案 1 :(得分:0)

var binding = new Binding("CanConnect") {
   Converter = new IsConnectedConverter()
};
DataGridTextColumn column = new DataGridTextColumn() { Header = "Can Connect", Binding = binding };

答案 2 :(得分:0)

要设置Converter,您可以使用Converter类的Binding属性:

DataGridTextColumn column = new DataGridTextColumn();
column.Header = "Can Connect";
Binding binding = new Binding("CanConnect");
binding.Converter = new IsConnectedConverter();
column.Binding = binding;

你不应该将switch用于布尔变量。这样更好:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    bool input = (bool)value;
    if (input)
    {
       return DependencyProperty.UnsetValue;
    }
    return Brushes.Red;
}

答案 3 :(得分:0)

只是添加到此。我需要将Converter设置为样式的绑定而不是列的绑定:

        Binding columnBinding = new Binding("CanConnect");
        Binding styleBinding = new Binding("CanConnect") { Converter = new IsConnectedConverter()}; 
        Style st = new Style(typeof(DataGridCell));
        st.Setters.Add(new Setter(Control.BackgroundProperty, styleBinding));
        column.CellStyle = st;
        column.Binding = columnBinding;
        dataGrid.Columns.Add(column);