Michael
Michael

Reputation: 2128

Storyboard animation

I made a small WPF application to slide UserControls in and out, the problem I have is when a UserControl animated to slide in, then I click the button to slide another UserControl in, they both slide out - I'm not sure why this is?

public UserControl1()
{
    InitializeComponent();
}

public void SlideIn(UserControl uc)
{
    ThicknessAnimation tAnimation = new ThicknessAnimation();
    tAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
    tAnimation.From = new Thickness(500, 0, -500, 0);
    tAnimation.To = new Thickness(0);
    tAnimation.DecelerationRatio = 0.9;

    Storyboard.SetTargetName(tAnimation, uc.Name);
    Storyboard.SetTargetProperty(tAnimation, new PropertyPath(MarginProperty));

    Storyboard storyboard = new Storyboard();
    storyboard.Children.Add(tAnimation);
    storyboard.Begin(uc);
    this.Content = uc;
}

public void SlideOut(UserControl uc)
{
    ThicknessAnimation tAnimation = new ThicknessAnimation();
    tAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
    tAnimation.To = new Thickness(-500, 0, 500, 0);
    tAnimation.DecelerationRatio = 0.9;

    Storyboard.SetTargetName(tAnimation, uc.Name);
    Storyboard.SetTargetProperty(tAnimation, new PropertyPath(MarginProperty));

    Storyboard storyboard = new Storyboard();
    storyboard.Children.Add(tAnimation);
    storyboard.Begin(this);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    SlideOut(userControl1);
    UserControl2 uc2 = new UserControl2();
    SlideIn(uc2);
}

Upvotes: 2

Views: 1890

Answers (1)

Clemens
Clemens

Reputation: 128013

Do you set the Name property of the UserControl somewhere? Or to be more precise, do you give the second UserControl a different Name than the first one? Your animations get their target set by

Storyboard.SetTargetName(tAnimation, uc.Name);

so names should be different. Alternatively you may call

Storyboard.SetTarget(tAnimation, uc);

to specify the target.

Upvotes: 1

Related Questions