2014-02-26 133 views
0

我有一个DataGrid动态生成列,我需要更改一些操作后,其值已更改的单元格的样式。WPF DataGrid单元格更改后更改

的的ItemsSource为数据网格定义为List<MyTableRow>,其中

public class MyTableRow 
{ 
    private string[] _values; 
    private string _rowHeader; 

    // getters and setters here 
} 

数据网格列与下面的代码生成:

for (int i = 0; i < source[0].Values.Length; i++) 
{ 
    var col = new DataGridTextColumn(); 
    var binding = new Binding("Values[" + i + "]"); 
    col.Binding = binding; 
    col.CanUserSort = false; 
    this.dataGrid.Columns.Add(col); 
    this.dataGrid.Columns[i].Header = columnNames[i]; 
} 

所得数据网格貌似this

,就会出现问题,当我尝试突出显示(粗体文本或彩色背景)其ItemsSource中的值已更改的单元格。这是我的问题,我的问题分裂成两部分:

  1. 是否有一些“内置”的方式来执行与更改的单元格? (可能与ObservableColletion否则水木清华)
  2. 如果没有,我怎么能突出或者基于其索引或他们的价值观不同的电池

我试着用XAML的风格和/或触发器来做到这一点,但事实证明原来我不知道我应该通过什么样的价值致盲到转换器结合或只是不工作的SO要么有同样的“问题”发现

<Style TargetType="TextBlock"> 
    <Setter Property="Background" 
      Value="{Binding <!-- some proper binding here -->, 
        Converter={StaticResource ValueToBrushConverter}}"/> 
</Style> 

其他解决方案。我能做些什么来突出显示一个单元而不是整行/列?如有必要,我可以更改ItemsSource,MyTableRow字段和/或列的生成代码

任何人都可以请我帮忙吗?去过几天,因为我坚持了这个问题


UPDATE找到解决方案


回答

0

最后找出如何做我想做的。解决方案有点“脏”,但对我来说工作得很好。 我添加非中断空格字符的每一个细胞,我需要强调

private const string NBSP = "\u00A0"

所有剩下要做之后是创造价值的转换器。所以,我在XAML添加MultiBinding

<DataGrid.CellStyle> 
    <Style TargetType="{x:Type DataGridCell}"> 
     <Setter Property="Background"> 
      <Setter.Value> 
       <MultiBinding Converter="{StaticResource ValueToBrushMultiConverter}" > 
        <MultiBinding.Bindings> 
         <Binding RelativeSource="{RelativeSource Self}" /> 
         <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridRow}}" /> 
        </MultiBinding.Bindings> 
       </MultiBinding 
      </Setter.Value> 
     </Setter> 
    </Style> 
</DataGrid.CellStyle> 

Сonverter定义为:

public class ValueToBrushMultiConverter : IMultiValueConverter 
    { 
     private const string NBSP = "\u00A0"; 
     public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      var cell = (DataGridCell)values[0]; 
      var dgRow = (DataGridRow)values[1]; 

      var test = (dgRow.Item as TableRow<string, string>).Values[cell.Column.DisplayIndex]; 

      if (test.Contains(NBSP)) 
       return System.Windows.Media.Brushes.PaleGreen; 
      return DependencyProperty.UnsetValue;   
     } 

     public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) 
     { 
      throw new NotSupportedException(); 
     } 
    } 

希望这可以帮助别人!

相关问题