Dipika
Dipika

Reputation: 409

How to change background of DataGrid row depending on value in one column

I have one DataGrid which contains one column for red or green color image. I do trigger to set red or green color image if status is ERROR or OK which comes from database. I just want to change color for whole row if there is red image.

I do XAML code to set Red of Green Image as below

<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> 

And I tried XAML code to change row background color as below

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

But It did not change background color. Please help me. When I google it I come to know solution about viewmodel and ObservableCollection(); but I have dynamic data which get from database.

Upvotes: 3

Views: 5500

Answers (2)

Dipika
Dipika

Reputation: 409

I got an answer. It's very easy by using loadingRow event of datagrid:

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

Upvotes: 2

Sagiv b.g
Sagiv b.g

Reputation: 31024

I wrote a simple demonstration for that RowStyle maybe it can help you.

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>

ViewModel:

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
}

a simple class:

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

Dispatcher class (to change the collection from the UI Thread taken from here):

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

and finally the converter:

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

Upvotes: 3

Related Questions