【问题标题】:How to change background of DataGrid row depending on value in one column如何根据一列中的值更改 DataGrid 行的背景
【发布时间】:2015-04-20 11:08:36
【问题描述】:

我有一个 DataGrid,其中包含一列红色或绿色图像。如果状态为来自数据库的 ERROR 或 OK,我会触发设置红色或绿色图像。如果有红色图像,我只想更改整行的颜色。

我做 XAML 代码来设置绿色图像的红色如下

<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <Image Name="IMG" Source="greenbuzz.png"/>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding Alarm}" Value="Error">
                <Setter TargetName="IMG" Property="Source" Value="redbuzz.png"/>
            </DataTrigger>             
        </DataTemplate.Triggers>         
    </DataTemplate>     
</DataGridTemplateColumn.CellTemplate> 

我尝试使用 XAML 代码更改行背景颜色,如下所示

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Alarm}" Value="ERROR">
                <Setter Property="Background" Value="Red" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.RowStyle>

但它没有改变背景颜色。请帮我。当我用谷歌搜索时,我了解了有关 viewmodel 和 ObservableCollection(); 的解决方案;但我有从数据库获取的动态数据。

【问题讨论】:

  • 你在哪里定义这种风格?
  • 样式在 标签...见我更新问题
  • 您的Trigger 代码似乎是正确的,因此要么您的数据错误,要么您的Binding Path 错误。您确定DataGrid 中的每个项目都有Active 属性吗?
  • 请关注更新...我有 1 列 Alarm 的值为 'error' 或 'ok' 。如果值为 ERROR,则背景色为红色。如果OK,则为绿色

标签: wpf wpfdatagrid


【解决方案1】:

我为那个RowStyle写了一个简单的演示,也许它可以帮助你。

XAML:

<Window x:Class="stackDatagridColor.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:viewModels="clr-namespace:stackDatagridColor"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <viewModels:viewmodel x:Key="viewmodel"/>
        <viewModels:BrushConverter x:Key="BrushConverter"/>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <DataGrid ItemsSource="{Binding Collection, Mode=TwoWay, Source={StaticResource viewmodel}, UpdateSourceTrigger=PropertyChanged}">
                <DataGrid.RowStyle>
                    <Style TargetType="DataGridRow">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Status}" Value="ERROR">
                                <Setter Property="Background" Value="Red"></Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding Status}" Value="OK">
                                <Setter Property="Background" Value="Green"></Setter>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </DataGrid.RowStyle>
            </DataGrid>
        </StackPanel>
    </Grid>
</Window>

视图模型:

public class viewmodel : INotifyPropertyChanged
{

    private ObservableCollection<myItem> collection;
    public ObservableCollection<myItem> Collection
    {
        get { return collection; }
        set { collection = value; OnPropertyChanged("Collection"); }
    }


    public viewmodel()
    {
        Collection = new ObservableCollection<myItem>();
        myItem item1 = new myItem { Name = "name1", Status = "OK" };
        myItem item2 = new myItem { Name = "name2", Status = "ERROR" };
        DispatchService.Invoke(() =>
            {
                Collection.Add(item1);
                Collection.Add(item2);
            });
    }


    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion
}

一个简单的类:

public class myItem
    {
        public string Status { get; set; }
        public string Name { get; set; }
    }

Dispatcher 类(更改来自here 的 UI 线程的集合):

public static class DispatchService
    {
        public static void Invoke(Action action)
        {
            Dispatcher dispatchObject = Application.Current.Dispatcher;
            if (dispatchObject == null || dispatchObject.CheckAccess())
            {
                action();
            }
            else
            {
                dispatchObject.Invoke(action);
            }
        }
    }

最后是转换器:

public class BrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string input = value as string;
        switch (input)
        {
            case "ERROR":
                return Brushes.Red;
            case "OK":
                return Brushes.Green;
            default:
                return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

【讨论】:

  • 感谢您提供如此详细的解决方案。但是我在获取视图模型和画笔转换器的名称空间时遇到问题。它给出了视图模型不在 namespace.projectname 中退出的错误。
  • 因为我的项目名称 (stackDatagridColor) 与您的不同。 x:Class="stackDatagridColor.MainWindow" xmlns:viewModels="clr-namespace:stackDatagridColor"。只需将您在 XAML 和 CS 上看到的 stackDatagridColor 更改为您的项目名称,或者只需创建一个与我选择的名称相同的新项目(stackDatagridColor)
  • yaaaa.. 我没有完全复制和害虫代码。我有另一个项目名称。作为nursemonitering 并适当使用 as x:class= "Nursemonitering.MainWindow" 和 xmlns:viewModels= "clr-namespace:nursemonitering"
  • 如果我没记错的话,xmlns:viewModels=... 指的是具有该名称的文件夹。所以BrushConverterandviewmodel 类应该在一个名为viewModels 的文件夹中。或者你可以根据你的结构重写XAML中的资源和xmlns。
  • 现在我在 ViewModel.cs 中收到错误,指出 Nurse "moniting.ViewModel" 没有实现接口成员 "system.ComponentModel.InotifyPropertyChange.ProprtyChange""
【解决方案2】:

我得到了答案。使用datagrid的loadingRow事件非常简单:

DataGridRow row = e.Row;
DataRowView rView = row.Item as DataRowView

if(rView != null && rView.Row.ItemArray[4].ToString().Contains("ERROR")) 
{
    e.row.Background= new SolidColorBrush(Color.Red);
}
else
{
    e.row.Background= new SolidColorBrush(Color.Green);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 2020-06-02
    • 2014-09-10
    • 2015-03-26
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    相关资源
    最近更新 更多