繁体   English   中英

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

[英]Binding WPF Datagrid cell background colour with trigger

我希望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属性,而不是仅设置当前文本块的背景颜色?

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

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

数据网格

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

其他人可以从代码隐藏方法中的WPF“动态数据触发器”中受益

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

    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是datagrid XAML名称,RowStyle设置为新样式。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM