开发者

Animation when changing ContentTemplate

开发者 https://www.devze.com 2023-04-07 05:04 出处:网络
I have a window where different controls had to be displayed over time. I searched for a solution with using the mvvm pattern and ended up with this

I have a window where different controls had to be displayed over time. I searched for a solution with using the mvvm pattern and ended up with this

<ContentControl Content="{Binding}">
        <ContentControl.Style>
            <Style TargetType="ContentControl">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ViewType}" Value="RecipeList">
                        <Setter Property="ContentTemplate" Value="{StaticResource RecipeTemplate}"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding ViewType}" Value="Default">
                        <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
</ContentControl>

This wor开发者_运维问答ks fine so far but i'm curious about two things:

  1. is there a better approach with mvvm?
  2. how can i execute an animation for the items in the new datatemplate that is about to be shown?


For the question #2:

You could use EventTrigger in controls within you templates to start animation like it is done below:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Triggers>
            <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                <BeginStoryboard>
                    <Storyboard x:Name="SomeStoryBoard"/>
                </BeginStoryboard>
            </EventTrigger>
        </Grid.Triggers>
    </Grid>
</Window>


Since Animations are View-Specific actions, they should be run from the Code-Behind the View, not the ViewModel. In the past, I've hooked into an Event and just run the following from the code-behind:

Storyboard animation = (Storyboard)panel.FindResource("MyAnimation");
animation.Begin();

As for question #1, I don't see any problem with your code for displaying a different View based on a property in the ViewModel.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号