在代码中动态添加IValueConverter

Bob*_*Bob 2 .net c# 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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

O. *_*per 5

使用Converter属性 的的Binding类:

new Binding("CanConnect") {
    Converter = new IsConnectedConverter()
}
Run Code Online (Sandbox Code Playgroud)

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

Style st = new Style(typeof(DataGridCell));
st.Setters.Add(new Setter(Control.BackgroundProperty, binding));
column.CellStyle = st;
Run Code Online (Sandbox Code Playgroud)

在该代码中,binding将是一个带有新Binding对象的变量(或者上面的构造函数和初始化调用).正如文档DataGridTextColumn.CellStyle所描述的那样,样式的目标类型必须是DataGridCell,并且当该类继承时Control,我们可以为依赖属性添加setter Control,例如Background.

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