【问题标题】:WPF Binding to DataGrid Context from CellStyleWPF 从 CellStyle 绑定到 DataGrid 上下文
【发布时间】:2015-11-04 15:05:47
【问题描述】:

我有一个 WPF DataGrid,它绑定到一个可观察的 RowObjects 集合,并带有一堆可绑定的属性。为了填写表格中的数据,我添加了绑定到 RowObjects 属性的 DataGridTextColumns。例如:

<DataGrid ItemsSource={Binding RowCollection}>
    <DataGrid.Columns>
        <DataGridTextColumn Header="Col1" Binding={Binding Property1Name, Mode=OneTime} IsReadOnly="True" />
        <DataGridTextColumn Header="Col2" Binding={Binding Property2Name, Mode=OneTime} IsReadOnly="True" />
        <DataGridTextColumn Header="Col3" Binding={Binding Property3Name, Mode=OneTime} IsReadOnly="True" />
    </DataGrid.Columns>
</DataGrid>

假设 Property3 是一个整数。我希望 Column3 中的单元格在负数时突出显示为红色,为零时为黄色,为正时为绿色。我的第一个想法是将 System.Windows.Media.Color 绑定到 DataGridTextColumn 的 CellStyle,但这似乎不能直接工作。有什么想法吗?

【问题讨论】:

    标签: c# wpf data-binding datagrid


    【解决方案1】:

    这并不容易,但是您可以为每个单元格使用转换器 背景

    一个单元格的样式:

    <Style x:Key="Col1DataGridCell" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding Converter={StaticResource Col1Converter}}" />
    </Style>
    

    一个单元格的转换器:

    public class Col1Converter : IValueConverter {
    
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
            var result = (RowObject)value;
    
            Color color;
            if (result.Value < 0) {
                color = Colors.Red;
            }
            else if (result.Value == 0) {
                color = Colors.Yellow;
            }
            else {
                color = Colors.Green;
            }
    
            return new SolidColorBrush(color);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
            throw new NotImplementedException();
        }
    }
    

    在 DataGrid 中使用:

    <DataGridTextColumn Header="Col1" Style={StaticResource Col1DataGridCell} Binding={Binding Property1Name, Mode=OneTime} IsReadOnly="True" />
    

    【讨论】:

    • 我提交了几乎相同的解决方案,晚了 17 秒...这次你赢了
    【解决方案2】:

    我建议你使用 Style 来改变单元格的颜色,在 IValueConverter 的帮助下

    检查这个:MSDN BLOG 并进行实验。

    祝你好运。

    【讨论】:

      猜你喜欢
      • 2014-07-20
      • 1970-01-01
      • 2013-10-14
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 2015-07-02
      相关资源
      最近更新 更多