首页 文章

WPF从CellStyle绑定到DataGrid上下文

提问于
浏览
1

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

<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,但这似乎没有直接起作用 . 有任何想法吗?

2 回答

  • 0

    这并不容易,但你可以为每个单元使用 Converter Background

    一个单元格的样式:

    <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" />
    
  • 1

    我建议你使用在IValueConverter的帮助下改变细胞颜色的Style

    检查一下:MSDN BLOG并进行实验 .

    祝你好运 .

相关问题