【问题标题】:Change Data bound WPF Datagrid row background/foreground color depending on the boolean property of an object根据对象的布尔属性更改数据绑定 WPF Datagrid 行背景/前景色
【发布时间】:2018-08-05 12:09:43
【问题描述】:

我在 WPF 应用程序中有一个 Datagrid(使用 MVVM {Caliburn Micro}),它绑定到 ObservableCollection<Student> 类型的属性,其中 Student 类如下所示:

public class Student
{
    public int ID { get; set; }
    public String FullName { get; set; }
    public bool Passed { get; set; }
}

根据事实 - 学生是否通过考试 - 我想将相应学生所在行的背景/前景更改为红色(如果未通过)。

下面显示了我的 DataGrid:

<DataGrid Grid.Column="1"
              RowBackground="White"
              Visibility="Visible"
              Grid.Row="15"
              ColumnWidth="auto"
              IsReadOnly="False"
              AutoGenerateColumns="False"
              BorderBrush="{StaticResource GridBorder}"
              VerticalScrollBarVisibility="Auto"
              HorizontalGridLinesBrush="LightGray"
              HorizontalScrollBarVisibility="Disabled"
              VerticalGridLinesBrush="LightGray"
              Name="Students"
              CanUserAddRows="True"  
              BorderThickness="0.8"
              SelectionUnit="FullRow"
              cal:Message.Attach="[Event MouseDoubleClick] = [Action GetRow($dataContext)]"
              SelectionMode="Single" Grid.ColumnSpan="4">   

这些是列定义:

<DataGridTextColumn Binding="{Binding ID}" Header="PersonalNumber"/>
<DataGridTextColumn Binding="{Binding FullName}" Header="FullName"/>

为了解决这个问题,我尝试了类似的方法,但不起作用:

<DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Passed}" Value="false">
                        <Setter Property="Background" Value="Red"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Passed}" Value="true">
                        <Setter Property="Background" Value="Black"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>

我能做什么?

【问题讨论】:

    标签: wpf datagrid row


    【解决方案1】:

    您的 DataGrid 正在设置覆盖 RowStyle 的 RowBackground="White",删除该设置,样式将按照您的预期运行。

    【讨论】:

    • 谢谢,我还没想好.. :)
    猜你喜欢
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2012-12-07
    • 2016-08-02
    • 2020-06-02
    • 2015-04-05
    • 1970-01-01
    • 2013-09-03
    相关资源
    最近更新 更多