Search code examples
c#wpfdatagrid

Disabling style triggers created in xaml programmatically


I am working on a c# WPF project which I am using a style trigger to style the background colour of the each row based on one of the cell values.

Below is my style trigger.

<Window.Resources>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Highest Alarm Level}" Value="Critical">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Highest Alarm Level}" Value="Medium">
                    <Setter Property="Background" Value="Orange" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Highest Alarm Level}" Value="Warning">
                    <Setter Property="Background" Value="Yellow" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Highest Alarm Level}" Value="Info">
                    <Setter Property="Background" Value="White" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>

What I need to be able to do, is under certain circumstances I don't want this style to be used, so what I am after, is if in the C# code a certain condition becomes to true, I want to disable all of the styling done above to not be used, i.e. all of the styling is turned off so the background colour of the rows are not set.


Solution

  • Add a Key to your custom DataGridRow Style

    <Style TargetType="DataGridRow" x:Key="MyRowStyle">
        <!-- Define Triggers -->
    </Style>
    

    Then you just need to switch between default and custom styles.

    If you set Style with null, that means the default Style will be applied

    dataGrid.RowStyle = _boolCondition ? this.FindResource("MyRowStyle") as Style : null;