Search code examples
wpfanimationmvvmdatatemplatevisualstatemanager

MVVM with animations (should I use VisualStateManager?)


I've got a View.xaml with the following set in Resources-section:

<DataTemplate DataType="{x:Type ViewModels:MyFirstViewModel}">
    <Views:MyFirstView Content="{Binding}" />
</DataTemplate>

<DataTemplate DataType="{x:Type ViewModels:MySecondViewModel}">
    <Views:MySecondView Content="{Binding}"/>
</DataTemplate>

In the content of the View.xaml I have:

<!-- SelectedMyViewModel is either set to MyFirstViewModel or MySecondViewModel -->
<ContentControl Content="{Binding SelectedMyViewModel}" />

When the SelectedMyViewModel changes I'd like to have a animation, so that the current view is faded out and the new view is faded in...

Somehow I feel this should be possible via the VisualStateManager - but I can't figure out how!

This is a WPF 4.0 project...


Solution

  • You maybe able to you the answer in this question to assist you WPF Fade Animation.

    They are doing a FadeIn/FadeOut on visibility. It might be possible to change the Trigger from...

    <Trigger Property="Visibility" Value="Visible">
    

    to...

    <Trigger Property="Content" Value="{x:Null}">
    

    So my idea would be that in transitioning between ViewModels you would do something like

    public void SwapViewModels()
    {
        // SelectedMyViewModel contains a MyFirstViewModel
        // Setting to null fires the Animation to fadeout
        SelectedMyViewModel = null;
    
        // Setting the Value to anything but null, should fire the fadein animation
        SelectedMyViewModel = new MySecondViewModel();
    }
    

    I haven't tested the code but hopefully it gives you a starting point.