如何根据一列中的值更改DataGrid行的背景

时间:2015-02-19 07:26:15

标签: wpf wpfdatagrid

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

我使用XAML代码将Red of Green Image设置为

<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()的解决方案;但我有来自数据库的动态数据。

2 个答案:

答案 0 :(得分:2)

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

enter image description here

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

答案 1 :(得分:1)

我得到了答案。使用datagrid的loadRow事件非常容易:

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