2016-09-28 4 views
1

데이터 셀 변수를 변경하려고합니다. 셀의 색을 선택하기 위해 셀과 행이 필요하므로 매개 변수로 셀을 가져올 변환기를 사용합니다. 따라서 데이터가 동적입니다. 어떤 모델도 가지고 있지 않습니다. 문제는 데이터를로드하는 동안 변환기가 맞지 않는 것입니다.변환기를 사용하여 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; 

     } 
    } 

이것은 DataGrid에 바인딩되는 스타일입니다.

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