How to animate an element where the trigger is a data change on the property you want to animate

Viewed 160

I want to animate my WPF window. It's set to size to content, so when the content changes, the window changes size. I don't want it to snap to a new size though, when it determines it needs a new size I want it to lerp between the old and new value with an animation.

How do I set this up?

EDIT: I am using SizeToContent=WidthAndHeight" as a parameter for my window, and want to animate when it automatically sizes to different content being shown.

1 Answers

You may override the OnPropertyChanged method and start an animation of any property you like.

For example, the Width property:

private DoubleAnimation widthAnimation;

protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
    if (e.Property == WidthProperty &&
        !double.IsNaN((double)e.OldValue) &&
        widthAnimation == null)
    {
        widthAnimation = new DoubleAnimation
        {
            Duration = TimeSpan.FromSeconds(1),
            From = (double)e.OldValue,
            To = (double)e.NewValue
        };

        widthAnimation.Completed += (s, a) =>
        {
            widthAnimation = null;
            BeginAnimation(WidthProperty, null);
        };

        BeginAnimation(WidthProperty, widthAnimation);
    }
    else
    {
        base.OnPropertyChanged(e);
    }
}
Related