javirs
javirs

Reputation: 1100

WPF animations inside user control

I have a user control that acts like a progress bar and animates the width of a rectangle as a response to an event. Someone arises the event with certain % and the rectangle width animates from its actual width to the % of the actualWidth of the user control.

IF I try to set the new width I get the "The calling thread cannot access this object because a different thread owns it." So I use the Dispatcher.Invoke and it runs nicely.

The problem appears if I try to animate the width change instead of just setting it. Then I get the different thread owns it error event when using the dispatcher.

So. This piece of code works nicely:

bar.Dispatcher.Invoke((Action)delegate { bar.Width = myWidth; });

But this piece of code does not:

DoubleAnimation widthAnimation = new DoubleAnimation();
widthAnimation.From = bar.ActualWidth;
widthAnimation.To = myWidth;
widthAnimation.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));
widthAnimation.RepeatBehavior = new RepeatBehavior(1);
bar.Dispatcher.Invoke( (Action)delegate {
    bar.BeginAnimation(Rectangle.WidthProperty, widthAnimation); 
});

So.. how am I suposed to run an animation on a user control like this one??

Thanks in advance !!!

Upvotes: 0

Views: 286

Answers (1)

Clemens
Clemens

Reputation: 128146

The animation should also be created in the UI thread:

bar.Dispatcher.Invoke((Action)delegate
{
    var widthAnimation = new DoubleAnimation
    {
        From = bar.ActualWidth,
        To = myWidth,
        Duration = TimeSpan.FromMilliseconds(500)
    };
    bar.BeginAnimation(Rectangle.WidthProperty, widthAnimation); 
});

Upvotes: 1

Related Questions