首页 > 解决方案 > 同时在同一个 ContentControl 上为两个 UserControl 设置动画

问题描述

我有这些LoadUnload动画App.xaml

<Storyboard x:Key="Unload">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)">
        <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
        <EasingDoubleKeyFrame KeyTime="0:0:3" Value="-800"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

<Storyboard x:Key="Load">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)">
        <EasingDoubleKeyFrame KeyTime="0" Value="800"/>
        <EasingDoubleKeyFrame KeyTime="0:0:3" Value="0"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

在我的代码中,我在 Button Clicks 上调用它们,如下所示:

sb1 = FindResource("Unload") as Storyboard;
sb2 = FindResource("Load") as Storyboard;

void Button_Click(object sender, RoutedEventArgs e)
{
    uc1.RenderTransform = GetTG();
    uc2.RenderTransform = GetTG();

    sb1.Begin(uc2);
    sb2.Begin(uc1);

    content.Content = uc1;
}

//and 

void Button_Click_1(object sender, RoutedEventArgs e)
{
    uc2.RenderTransform = GetTG();
    uc1.RenderTransform = GetTG();

    sb2.Begin(uc2);
    sb1.Begin(uc1);

    content.Content = uc2;
}

GetTG返回一个TransformGroup

TransformGroup GetTG()
{
    var tg = new TransformGroup();
    tg.Children.Add(new ScaleTransform());
    tg.Children.Add(new SkewTransform());
    tg.Children.Add(new RotateTransform());
    tg.Children.Add(new TranslateTransform());
    return tg;
}

只有这些Load动画作品。如何使两者同时工作?

标签: wpfrendertransform

解决方案


将动画应用到ContentControl. 这应该将当前的Content/UserControl滑出到左侧并从右侧滑入新的Content/ UserControl

void Button_Click(object sender, RoutedEventArgs e)
{
    UnLoadAndLoad(uc1);
}

void Button_Click_1(object sender, RoutedEventArgs e)
{
    UnLoadAndLoad(uc2);
}

void UnLoadAndLoad(object ucToBeLoaded)
{
    if (content.Content != ucToBeLoaded)
    {
        content.RenderTransform = GetTG();

        EventHandler completed = null;
        completed = (ss, ee) =>
        {
            sb1.Completed -= completed;
            content.Content = ucToBeLoaded;
            //load
            sb2.Begin(content);
        };
        sb1.Completed += completed;
        //unload

        if (content.Content != null)
            sb1.Begin(content);
        else
            completed(this, EventArgs.Empty);
    }
}

推荐阅读