2015-11-04 112 views
1

我有一个绑定到RowObjects的可观察集合的WPF DataGrid,它具有一组可绑定属性。为了填充表格中的数据,我添加了DataGridTextColumns,它们绑定到RowObjects的属性。例如:WPF绑定到CellStyle的DataGrid上下文

<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,但这似乎并不直接工作。有任何想法吗?

回答

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" /> 
+0

我已经提出了几乎相同的解决方案,晚了17秒...你赢了这次 – Jose

0

我会建议你使用风格会改变细胞的颜色用的IValueConverter

入住此帮助:MSDN BLOG和实验。

祝你好运。