Click here to Skip to main content
15,923,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I need to add background color depending on the value inside the column. I was able to do it from XAML file. But now i am creating the grid everything dynamically from code behind. Not sure on how to add the background to a particular cell programmatically. Below is the code i have written in XAML

What I have tried:

<GridViewColumn Header="Result">
       <GridViewColumn.CellTemplate>
          <DataTemplate>
           <TextBlock x:Name="Result" Text="{Binding Path=Result}" />
           <DataTemplate.Triggers>
           <DataTrigger Binding="{Binding Path=Result}" Value="Fail">
          <Setter TargetName="Result" Property="Background" Value="Red" />
           </DataTrigger>
           <DataTrigger Binding="{Binding Path=Result}" Value="Pass">
          <Setter TargetName="Result" Property="Background" Value="Green" />
          </DataTrigger>
          </DataTemplate.Triggers>
          </DataTemplate>
          </GridViewColumn.CellTemplate>
 </GridViewColumn>
Posted
Updated 13-Feb-23 7:53am

1 solution

It seems you can use a converter to convert your Boolean value to right background specified in your App.Resources -

<GridViewColumn Width ="50" Header="GEN" >
    <GridViewColumn.CellTemplate>
         <DataTemplate>
              <TextBlock Text="{Binding Path=Gen}" Background="{Binding Gen, Converter={StaticResource BackgroundConverter}}" />
         </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>


The Converter will look something like -
class BackgroundConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && value is bool && (bool)value)
        {
            return Application.Current.FindResource("ActiveBrush");
        }

        return Application.Current.FindResource("DefaultBrush");
    }

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


Add the brushes in your App.Resources -
<SolidColorBrush x:Key="DefaultBrush" Color="Red" />
<SolidColorBrush x:Key="ActiveBrush" Color="Yellow" />
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900