我正在使用 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 模式呢?
最佳答案
我假设您的 DataGrids ItemsSource 绑定(bind)到 Log4NetLog 的集合,因此您可以在 xaml 中进行样式设置:
<DataGrid.ItemContainerStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Background" Value="{Binding Path=LogColour.Colour}"/>
</Style>
</DataGrid.ItemContainerStyle>
也许您需要一个 Color 到 SolidColorBrush 转换器。
关于c# - DataGrid行背景色MVVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14997250/