DataGridTextColumn的WPF绑定背景色由色行 [英] WPF bind background color of DataGridTextColumn to color by row

查看:3310
本文介绍了DataGridTextColumn的WPF绑定背景色由色行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有下列数据的DataGrid中:

 约翰,男
玛丽女
托尼,男
莎莉,女

网格势必Person模型的一个ObservableCollection实现INofifyPropertyChanged的性能Person.Name和Person.Gender对象。我现在想的DataGridTextColumn的背景色绑定到人的性别,使含雄性行是蓝色的,和含有雌性行是粉红色的。

 公共类Person 
{$:是否有可能通过增加另一个属性到Person模型像这样做b $ b酒店的公共颜色BackgroundColor中
{
得到
{
如果(性别==男)
{
返回Color.Blue;
}
,否则
{
返回Color.Pink;
}
}
}

如果是这样,我该怎么办绑定这行或列的背景颜色?我已经有界的列是这样的:

 <一个DataGridColumn标题=名称绑定= {绑定名} /> 
<一个DataGridColumn标题=性别绑定= {结合性别} />


解决方案

假设 BackgroundColor中是的 System.Windows.Media.Color 键入,而不是的System.Drawing.Color 如果你想改变整行的背景,你可以改变 DataGrid.RowStyle 和绑定背景属性 BackgroundColor中属性

 < D​​ataGrid中...> 
< D​​ataGrid.RowStyle>
<风格的TargetType ={X:类型DataGridRow}>
< setter属性=背景>
< Setter.Value>
<的SolidColorBrush颜色={绑定路径= BackgroundColor中}/>
< /Setter.Value>
< /二传手>
< /样式和GT;
< /DataGrid.RowStyle>
< / DataGrid的>


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

解决方案

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>

这篇关于DataGridTextColumn的WPF绑定背景色由色行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆