2015-03-19 17 views
0

我需要通過代碼來此XAML樣式應用於DataGrid的細胞:應用樣式到DataGridCell編程與轉換器

<DataGrid.RowStyle> 
    <Style TargetType="DataGridRow"> 
     <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Self}, Path=Item.Dif, Converter={StaticResource RedValues}}"/> 
    </Style> 
</DataGrid.RowStyle> 

到目前爲止,在我的代碼,我可以申請在TextAlignmentProperty一個二傳手,但沒有對前景:

Style style2 = new Style(typeof(DataGridCell)); 
style2.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right)); 
style2.Setters.Add(new Setter(TextBlock.ForegroundProperty, new RedValues())); 

codb = new DataGridTextColumn(); 
codb.Binding = new Binding("Dif") { 
    StringFormat = "C", 
    ConverterCulture = new CultureInfo("pt-PT") }; 
codb.Header = "Dif"; 
codb.CellStyle = style2; 
grid.Columns.Add(codb); 

這是我的轉換器類:

class RedValues: IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      if (value is decimal) { 
       decimal quantity = (decimal)value; 
       if (quantity < 0) 
        return Brushes.IndianRed; 
       if (quantity > 0) 
        return Brushes.ForestGreen; 
       return Brushes.Black; 
      } 

      return Brushes.Yellow; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 
+0

你的天堂」在代碼中應用任何轉換器?你的問題到底是什麼? – Muds 2015-03-19 11:42:42

+0

是如何應用轉換器 – celsoap7 2015-03-19 11:43:27

+0

我猜ans應該幫助:) – Muds 2015-03-19 11:49:38

回答

1

你可以做點事荷蘭國際集團這樣的,如果你想分配與代碼轉換器的綁定..

style2.Setters.Add(new Setter(TextBlock.ForegroundProperty, new Binding("Item.Dif"){Converter = new RedValues()}))}; 

爲你的情況 - 當你覺得你可以添加所有相關代碼和路徑綁定..

+0

非常感謝。我需要以編程方式創建DataGrid以便打印一些數據,並且在紅色中具有負值是必須的:) – celsoap7 2015-03-19 13:46:41

+0

現在您擁有它了:) – Muds 2015-03-19 13:53:34