gpt4 book ai didi

c# - WPF 将 DataGridTextColumn 的背景颜色绑定(bind)到按行着色

转载 作者:行者123 更新时间:2023-11-30 19:56:39 25 4
gpt4 key购买 nike

假设我有一个包含以下数据的 DataGrid:

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

网格绑定(bind)到 Person 模型对象的 ObservableCollection,该对象为属性 Person.Name 和 Person.Gender 实现了 INofifyPropertyChanged。我现在想将 DataGridTextColumn 的背景颜色绑定(bind)到人的性别,这样包含男性的行是蓝色的,包含女性的行是粉红色的。是否可以像这样通过向 Person 模型添加另一个属性来做到这一点:

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

如果是这样,我如何将它绑定(bind)到行或列的背景颜色?我已经有这样的边界列:

<DataGridColumn Header="Name" Binding={Binding Name} />
<DataGridColumn Header="Gender" Binding={Binding Gender} />

最佳答案

假设 BackgroundColorSystem.Windows.Media.Color 类型,而不是 System.Drawing.Color,如果您想要要更改整行的背景,您可以更改 DataGrid.RowStyle 并将 Background 属性绑定(bind)到 BackgroundColor 属性

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

关于c# - WPF 将 DataGridTextColumn 的背景颜色绑定(bind)到按行着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33309271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com