2016-09-28 54 views
1

我想通過使用將獲取單元格作爲參數的轉換器來更改datagrid單元格顏色,因爲我需要單元格和行來選擇單元格的顏色。因此數據是動態的沒有任何模型。問題是轉換器在加載數據時不會受到影響。使用轉換器的Datagrid單元格顏色更改

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; 

     } 
    } 

這是綁定到數據網格的樣式。

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

轉換器:

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

回答

0

這爲我工作:

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