2011-08-11 9 views
0

私はバインディングにはかなり新しく、一般的にはWPFです。、バインドされた行の色をDataGridに変更する

私はXAMLビューでDataGridを作成しました。次に、2つのDataGridTextColumnsを作成しました。

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

次に、データグリッドに列を追加します。私は、データグリッドに新しい項目を追加したい場合は、私はちょうど行うことができ、

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

例を追加しました。それは喜んで:) –

関連する問題