DataGrid row Background color MVVM

2019-07-21 07:54发布

Im using MVVM architecture and I want to change the row color in a datagrid. The color of row depends on the item from the model.

so far I have this Code:

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);
        }
}

As you can see, in the second Line I have to make an reference to a Log4NetLog which is in the model.

So how can I change the code to adapt the MVVM pattern?

1条回答
不美不萌又怎样
2楼-- · 2019-07-21 08:00

I assume your DataGrids ItemsSource is bound to an Collection of Log4NetLog's, so you can do styling in xaml:

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

Maybe you need a Color to SolidColorBrush Converter.

查看更多
登录 后发表回答