2011-08-11 51 views
0

我对绑定和WPF一般都很陌生。在WPF中,将绑定行的颜色更改为DataGrid

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

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

然后我将这些列添加到dataGrid中。当我想以一个新的项目添加到数据网格,我可以做,

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

这是伟大的,工作正常(我知道有很多方法可以做到这一点,但是这是最简单的我现在)。

但是,当我尝试做下一件事情时,问题会发生;

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

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

我建议你创建尽可能在XAML,例如列。 –

回答

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)); 
     } 
    } 
} 
+0

非常感谢。但是,你能给我一个在这种情况下工作的财产的例子('ACondition') – MichaelMcCabe

+0

非常感谢你:) – MichaelMcCabe

+0

增加了一个例子;很高兴帮助:) –