c# - DataGrid行背景色MVVM

标签 c# wpf 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 模式呢?

最佳答案

我假设您的 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/

相关文章:

c# - System.Net.SmtpClient SendAsync() 方法的内部实现

c# - 这是什么语法,将接口(interface)初始化为类数组? (新的 IItemTransform[0])

c# - 通过双击名称来更改 TabItem 的名称

c# - 可以将 View 传递给 MVVM 中的 ViewModel 吗?

wpf - 错误 : This PlotModel is already in use by some other PlotView control

c# - 如何使用 C# 和 Newtonsoft JSON 求和值?

c# - Git 忽略对文件的更改但将其保留在 repo 协议(protocol)中

c# - 在 WPF 中使用 Linq 的正确方法

c# - 焦点抽象

c# - 如何将 MvxCommand 附加到 BottomBar?