2015-11-04 104 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和實驗。

祝你好運。