在WPF中,将绑定行的颜色更改为DataGrid

时间:2011-08-11 12:11:01

标签: c# wpf xaml datagrid

我对绑定很新,而且一般都是WPF。

现在我在XAML视图中创建了一个DataGrid。然后我创建了两个DataGridTextColumns

DataGridTextColumn col1 = new DataGridTextColumn();
        col1.Binding = new Binding("barcode");

然后我将列添加到dataGrid。当我想向datagrid添加一个新项目时,我可以这样做,

dataGrid1.Items.Add(new MyData() { barcode = "barcode", name = "name" });

这很棒并且工作正常(我知道有很多方法可以做到这一点,但现在这对我来说是最简单的。)

然而,当我尝试做下一件事时问题就出现了;

我想将这些项添加到dataGrid,但根据特定条件使用不同的前景颜色。我 -

if (aCondition)
  dataGrid.forgroundColour = blue;
  dataGrid.Items.Add(item);

1 个答案:

答案 0 :(得分:3)

使用触发器例如:

<DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ACondition}" Value="True">
                <Setter Property="TextElement.Foreground" Value="Blue" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.RowStyle>

为此,您的项目当然需要有一个名为ACondition的属性。

编辑:一个示例(假设您可能希望在运行时更改属性,从而实现INotifyPropertyChanged

public class MyData : INotifyPropertyChanged
{
    private bool _ACondition = false;
    public bool ACondition
    {
        get { return _ACondition; }
        set
        {
            if (_ACondition != value)
            {
                _ACondition = value;
                OnPropertyChanged("ACondition");
            }
        }
    }

    //...

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
相关问题