C# DataGrid行背景色MVVM

C# DataGrid行背景色MVVM,c#,wpf,mvvm,datagrid,C#,Wpf,Mvvm,Datagrid,我正在使用MVVM体系结构,我想更改datagrid中的行颜色。 行的颜色取决于模型中的项目 到目前为止,我有以下代码: private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e) { Log4NetLog dataGridRow = e.Row.DataContext as Log4NetLog; if (highlight) { if (dataGrid

我正在使用MVVM体系结构,我想更改datagrid中的行颜色。 行的颜色取决于模型中的项目

到目前为止,我有以下代码:

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绑定到Log4NetLog的集合,因此您可以在xaml中进行样式设置:

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


也许你需要一个颜色到SolidColorBrush的转换器。

你能发布更多的代码吗?高光来自哪里?为了适应MVVM模式,您可以设置DataGridRow模板,根据与DataContext ViewModel中属性的绑定来修改背景颜色的值。检查。突出显示只是一个布尔值。。。你可以忽略它。它不是imoportantOk,但本质上您需要viewmodel中的某些属性,您可以通过ValueConverter绑定这些属性以返回颜色。