2013-02-21 119 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转换器。