2016-09-28 3 views
1

Ich versuche, Datagrid Zellfarbe zu ändern, indem Sie einen Konverter, der die Zelle als Parameter erhalten, weil ich die Zelle und Zeile, um die Farbe der Zelle wählen müssen. Die Daten sind dynamisch daher ich don Habe kein Modell. Problem ist, dass der Konverter beim Laden von Daten nicht getroffen wird.Datagrid Zelle Farbwechsel mit Konverter

private void RDataGrid_AutoGeneratedColumns(object sender, EventArgs e) 
    { 
     foreach (var dataGridColumn in RDataGrid.Columns) 
     { 
      var textColumn = dataGridColumn as DataGridTextColumn; 
      if (textColumn == null) continue; 

      textColumn.ElementStyle = FindResource("gridElementStyle") as Style; 
      textColumn.EditingElementStyle = FindResource("gridEditElementStyle") as Style; 
      textColumn.CellStyle = FindResource("gridCellStyle") as Style; 

     } 
    } 

Dies ist der Stil, der an Datagrid gebunden ist.

<Style x:Key="gridCellStyle" TargetType="{x:Type DataGridCell}"> 
    <Setter Property="Background" 
         Value="{Binding . 
         , RelativeSource={RelativeSource AncestorType={x:Type DataGridCell}} 
         ,Converter={StaticResource ColorConverter} 
          }" /> 
</Style> 

Converter:

public class ColorConverter : IValueConverter 
{ 
    //private string[,] yourarray = new string[100, 100]; 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     DataGridCell cell = (DataGridCell)value; 
     return Brushes.Red; 
     //int x = cell.Column.DisplayIndex; 
     //var parent = VisualTreeHelper.GetParent(cell); 
     //while (parent != null && parent.GetType() != typeof(DataGridRow)) 
     //{ 
     // parent = VisualTreeHelper.GetParent(parent); 
     //} 
     //int y = ((DataGridRow)parent).GetIndex(); 

    } 

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

Antwort

0

Das ist für mich gearbeitet:

<Style TargetType="DataGridCell"> 
           <Setter Property="Foreground" Value="Black"/> 
           <Setter Property="Background"> 
            <Setter.Value> 
             <MultiBinding Converter="{StaticResource NameToBrushMultiValueConverter}" > 
              <MultiBinding.Bindings> 
               <Binding RelativeSource="{RelativeSource AncestorType=Window}" Path="DataContext"/> 
               <Binding RelativeSource="{RelativeSource AncestorType=DataGrid}"></Binding> 
               <Binding RelativeSource="{RelativeSource Self}"/> 
              </MultiBinding.Bindings> 
             </MultiBinding> 
            </Setter.Value> 
           </Setter> 
          </Style>