问题
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:
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.
来源:https://stackoverflow.com/questions/14997250/datagrid-row-background-color-mvvm