2013-02-21 149 views
1

我使用MVVM架構,我想更改數據網格中的行顏色。 行的顏色取決於模型中的項目。DataGrid行背景顏色MVVM

到目前爲止,我有這樣的代碼:

private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e) { 
     Log4NetLog dataGridRow = e.Row.DataContext as Log4NetLog; 
     if (highlight) { 
      if (dataGridRow != null) { 
       e.Row.Background = new SolidColorBrush(
        dataGridRow.LogColour.Colour); 
      } 
     } else { 
      e.Row.Background = new SolidColorBrush(Colors.White); 
     } 
} 

正如你可以看到,在第二行我必須做出一個Log4NetLog這是在模型的參考。

那麼,如何更改代碼以適應MVVM模式呢?

+0

你能爲此發佈更多的代碼嗎?重點來自哪裏?爲了適應MVVM模式,可以設置DataGridRow模板,根據綁定到DataContext ViewModel中的屬性來修改背景顏色的值。查看http://msdn.microsoft.com/en-us/library/cc278066%28v=vs.95%29.aspx。 – Dutts 2013-02-21 08:25:59

+0

高亮只是一個布爾值......你可以忽略它。它不是imoportant – RayOldProf 2013-02-21 08:36:44

+0

好吧,但基本上你需要在你的viewmodel中你可以綁定到的一些屬性,通過ValueConverter返回一個顏色。 – Dutts 2013-02-21 08:39:15

回答

2

我假設你的DataGrid的ItemsSource綁定到Log4NetLog的一個集合,所以你可以在XAML做造型:

 <DataGrid.ItemContainerStyle> 
      <Style TargetType="{x:Type DataGridRow}"> 
       <Setter Property="Background" Value="{Binding Path=LogColour.Colour}"/> 
      </Style> 
     </DataGrid.ItemContainerStyle> 

也許你需要一種顏色的SolidColorBrush轉換器。