基于类属性在代码中设置DataGrid单元格样式

时间:2014-11-18 16:40:05

标签: wpf datagrid .net-4.5

我有一个绑定到数组的DataGrid,并根据数组的大小在运行时生成列:

ObservableCollection<DisplayByte[]> items = new ObservableCollection<DisplayByte[]>();

// List is populated
... 
...

Style style = new Style(typeof(TextBlock));

Setter setter = new Setter(TextBlock.ForegroundProperty, Brushes.LightGreen);

DataTrigger trigger = new DataTrigger() { Binding = new Binding("IsEqual"), Value = true };

trigger.Setters.Add(setter);
style.Triggers.Add(trigger);

dgBlobViewer.Columns.Add( new DataGridTextColumn
                          { 
                              Header = "",
                              Binding = new Binding(string.Format("[{0}].Value", columnIndex++)),
                              ElementStyle = style
                          });

DisplayByte类是这样的:

public class DisplayByte : INotifyPropertyChanged 
{
    private bool m_isequal;
    public DisplayByte(string value)
    {
        Value = value;
        IsEqual = false;
    }

    public String Value
    {
        get;
        set;
    }

    public Boolean IsEqual
    {
        get
        {
            return m_isequal;
        }
        set
        {
            m_isequal = value;
            OnPropertyChanged(new PropertyChangedEventArgs("IsEqual"));
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, e);
        }
    }
}

绑定工作正常,因此我在datagrid单元格上显示Value Property的值。我想设置单元格的样式,因此如果IsEqual属性为true,它们的背景会改变,但它不起作用。所有细胞总是白色的。

Datagrid的XAML是这样的:

<DataGrid x:Name="dgBlobViewer" 
          Grid.Row="0" 
          Grid.RowSpan="1" 
          Margin="10,10,10,0" 
          ItemsSource="{Binding}"
          AutoGenerateColumns="False"
          FontFamily="Consolas" >

绑定或样式有什么问题吗?

1 个答案:

答案 0 :(得分:1)

IsEqual属性属于 数据项 ,因此在这种情况下您必须使用DataTrigger

var trigger = new DataTrigger();
trigger.Binding = new Binding("[index].IsEqual");//index is placeholder.
trigger.Value = true;
trigger.Setters.Add(setter);
style.Triggers.Add(trigger);