Search code examples
c#uwpuwp-xamlvisualstatemanageradaptive-trigger

UWP disable visual state or remove trigger


I have a UWP app and have a visual state trigger in xaml like so

<VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="WindowStates">
                <VisualState x:Name="WideState">
                    <VisualState.StateTriggers>
                        <AdaptiveTrigger MinWindowWidth="850" />
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <!-- <Setter Target="MenuGrid.Grid.Background" Value="LightYellow" /> -->
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="NarrowState"> ...

Now i would like to disable one of the visual states or remove the trigger completely programmatically in code. Is there a way of doing that?


Solution

  • Here's how to remove them completely.

    // Stop the child Storyboad if there's one.
    MyVisualState.Storyboard?.Stop();
    
    // Remove all triggers.
    foreach (var trigger in MyVisualState.StateTriggers)
    {
        MyVisualState.StateTriggers.Remove(trigger);
    }
    

    However, I'd use the approach below so I can remove and add them back later. You will need to name all your AdaptiveTriggers first.

    // Remove a specific trigger.
    MyVisualState.StateTriggers.Remove(MyTrigger);
    
    // Add it back.
    MyVisualState.StateTriggers.Add(MyTrigger);