Binding WPF Datagrid cell background colour with trigger

后端 未结 2 425
耶瑟儿~
耶瑟儿~ 2021-01-02 00:33

I want the background colour of a WPF datagrid cell to change colour when the contents have been modified. Each cell has behind it a ViewModel object which contains the foll

相关标签:
2条回答
  • 2021-01-02 00:41

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

    This code allows users to highlight data rows with the specified text they want.

        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");
    
    • The parm CurrentTextToFilter the text the user entered into a XAML Textbox.Text property that was bound to the code behind.

    • The variable XDG is the datagrid XAML name and the RowStyle is set to the new style.

    • Make sure to add the setter to the DataTrigger as shown. If you add it directly to the Rowstyle, all the rows will turn red.
    0 讨论(0)
  • 2021-01-02 00:54

    You need to set CellStyle to target DataGridCell instead of only TextBlock.

    If you want this dataTrigger to be applied for all cells in your dataGrid, set style on DataGrid CellStyle otherwise you can do that on specific DataGridTextColumn CellStyle as well.

    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>
    
    0 讨论(0)
提交回复
热议问题