首页 文章

使用触发器绑定WPF Datagrid单元格背景颜色

提问于
浏览
10

我希望WPF数据网格单元格的背景颜色在修改内容时更改颜色 . 每个单元格后面都有一个ViewModel对象,该对象包含以下属性 - Value,OriginalValue和Modified . 当用户编辑单元格内容时,这会通过数据绑定自动触发Amount属性 . 然后,此属性setter将其与原始值进行检查,并将boolean Modified属性分别设置为true或false,通知绑定以更新这些属性 .

到目前为止,我已经使用DataGridTextColumn的ElementStyle属性上的Style获得了部分结果,如下所示

<Style x:Key="DataGridTextStyle" TargetType="{x:Type TextBlock}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=MyViewModel.Modified}" Value="True">
            <Setter Property="Background" Value="Yellow"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

这会更新文本内容背景颜色,但这只是单元格中心的一个小区域 . 我希望整个单元格更新它的背景颜色,而不仅仅是textblock属性 .

我是否可以修改上面的触发器以在可视树中向上搜索以查找父DataGridCell并在其上设置Background属性,而不是仅设置当前文本块的背景颜色?

2 回答

  • 4

    您需要将 CellStyle 设置为目标 DataGridCell 而不是仅 TextBlock .

    如果您希望将此dataTrigger应用于dataGrid中的所有单元格,请在 DataGrid CellStyle 上设置样式,否则您也可以在特定的 DataGridTextColumn CellStyle 上执行此操作 .

    DataGrid

    <DataGrid>
            <DataGrid.CellStyle>
                <Style TargetType="DataGridCell">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding MyViewModel.Modified}"
                                     Value="True">
                            <Setter Property="Background" Value="Yellow"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.CellStyle>
        </DataGrid>
    

    DataGridTextColumn

    <DataGrid>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Name}">
                    <DataGridTextColumn.CellStyle>
                        <Style TargetType="DataGridCell">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding MyViewModel.Modified}" 
                                             Value="True">
                                    <Setter Property="Background" Value="Yellow"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </DataGridTextColumn.CellStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    
  • 18

    Others May benefit from this WPF "Dynamic Data Triggers" in code behind method

    此代码允许用户使用所需的指定文本突出显示数据行 .

    var st = new Style();
        st.TargetType = typeof(DataGridRow);
        var RedSetter = new Setter( DataGridRow.BackgroundProperty, Brushes.Red);
        var dt = new DataTrigger(){
            Value = CurrentTextToFilter,
            Binding = new Binding("Value")               
        };
        dt.Setters.Add(RedSetter);
        st.Triggers.Add(dt);
        XDG.RowStyle = st;
        PropChanged("MainDataCollection");
    
    • parm CurrentTextToFilter用户输入的文本绑定到后面的代码的XAML Textbox.Text属性 .

    • 变量XDG是数据网格XAML名称,RowStyle设置为新样式 .

    • 确保将setter添加到DataTrigger,如图所示 . 如果将其直接添加到Rowstyle,则所有行都将变为红色 .

相关问题