简体   繁体   English

WPF从CellStyle绑定到DataGrid上下文

[英]WPF Binding to DataGrid Context from CellStyle

I have a WPF DataGrid that is bound to an observable collection of RowObjects with a bunch of bindable properties. 我有一个WPF DataGrid,它绑定到具有许多可绑定属性的可观察到的RowObjects集合。 To fill out the data in my table, I added DataGridTextColumns which bind to the properties of the RowObjects. 为了填写表中的数据,我添加了DataGridTextColumns绑定到RowObjects的属性。 For example: 例如:

<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>

Let's say Property3 is an integer. 假设Property3是整数。 I want the cells in Column3 to highlight to red when they are negative, yellow when it's zero, and green when it's positive. 我希望Column3中的单元格在负数时突出显示为红色,在零时为黄色,在正数时为绿色。 my first thought was to bind a System.Windows.Media.Color to the CellStyle of the DataGridTextColumn, but that doesn't seem to work directly. 我的第一个想法是将System.Windows.Media.Color绑定到DataGridTextColumn的CellStyle,但这似乎并不直接起作用。 Any ideas? 有任何想法吗?

It's not easy, but you can use Converter for each cell Background 这并不容易,但你可以使用转换器为每个单元格背景

Style for one cell: 一个单元格的样式:

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

Converter for one cell: 一个单元的转换器:

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();
    }
}

Using in DataGrid: 在DataGrid中使用:

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

I would recommend you to use Style that would change color of cell with help of IValueConverter 我建议您使用可以通过IValueConverter更改单元格颜色的样式

Check this : MSDN BLOG and experiment. 检查此: MSDN BLOG并进行实验。

Best of luck. 祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM