0
votes

Could you please help with the binding.

I have four fields that are bound to a datagrid source using XAML binding. string field1, field2, field3 bool field4

I need to change the color of field3 to red based on value in field4 (which is a bool).

1
You'll probably want to use a DataTrigger on the DataGridCellTemplate. Should be able to find plenty of information online, or if you included your XAML I'm sure someone would help you out with the exact syntax you'd need. :) - Rachel

1 Answers

1
votes

You can use a converter to convert the boolean into a SolidColorBrush. A value converter does what its name implies: It converts one value into another. In your case, you want to convert a boolean to a SolidColorBrush, depending on what the boolean is.

Here's a short example on how to make a value converter and how to use it. It must implement the IValueConvert interface, located in System.Windows.Data. Usually, you only need to fully implement the Convert method.

class BooleanToBrush : IValueConverter
{
    Brush solidRed = new SolidColorBrush(Colors.Red);
    Brush empty = new SolidColorBrush();

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool showRed = (bool)value;
        if (showRed)
            return solidRed;
        else
            return empty;
    }

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

And then to use it:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <local:BooleanToBrush x:Key="b2b" />
</Window.Resources>
<Grid Background="{Binding someBooleanProperty, Converter={StaticResource b2b}}">
</Grid>

More information on value converters can be found here: http://www.wpftutorial.net/ValueConverters.html