3

我正在使用 .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

4 回答 4

7

使用类 的Converter属性Binding

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

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

Style st = new Style(typeof(DataGridCell));
st.Setters.Add(new Setter(Control.BackgroundProperty, binding));
column.CellStyle = st;

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

恐怕我现在无法测试这段代码;我希望它能给你一个关于如何进行的想法。

于 2012-08-24T12:12:40.460 回答
0

只是为了补充这一点。我需要在样式绑定而不是列绑定上设置转换器:

        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);
于 2012-08-28T14:01:24.953 回答
0
var binding = new Binding("CanConnect") {
   Converter = new IsConnectedConverter()
};
DataGridTextColumn column = new DataGridTextColumn() { Header = "Can Connect", Binding = binding };
于 2012-08-24T12:13:31.190 回答
0

对于设置转换器,您可以使用类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;
}
于 2012-08-24T12:14:10.347 回答