Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF bind background color of DataGridTextColumn to color by row

Say I have a DataGrid with the following data:

John, Male
Mary, Female
Tony, Male
Sally, Female

The grid is bound to an ObservableCollection of Person model objects that implements INofifyPropertyChanged for the properties Person.Name and Person.Gender. I now want to bind the DataGridTextColumn's background color to the person's gender so that rows containing males are blue, and rows containing females are pink. Is it possible to do this by adding another property to the Person model like so:

public class Person
{
    public Color BackgroundColor
    {
        get
        {
            if (gender == "Male")
            {
                return Color.Blue;
            }
            else
            {
                return Color.Pink;
            }
        }
    }

if so, how do I bind this to the row or column's background color? I already have bounded columns like this:

<DataGridColumn Header="Name" Binding={Binding Name} />
<DataGridColumn Header="Gender" Binding={Binding Gender} />
like image 649
user3685285 Avatar asked Nov 28 '25 15:11

user3685285


1 Answers

Assuming that BackgroundColor is of a System.Windows.Media.Color type, and not System.Drawing.Color, if you want to change background of the entire row you can alter DataGrid.RowStyle and bind Background property to BackgroundColor property

<DataGrid ...>
    <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="Background">
                <Setter.Value>
                    <SolidColorBrush Color="{Binding Path=BackgroundColor}"/>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>
like image 90
dkozl Avatar answered Nov 30 '25 05:11

dkozl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!