Begin animation when ContentControl.Content is changed

后端 未结 2 1193
暗喜
暗喜 2021-01-06 08:02

I\'m trying to fire an animation when a content control such as Button or ContentControl changes its content. My initial thoughts were to do this:

        &l         


        
2条回答
  •  既然无缘
    2021-01-06 08:50

    You can just write an attached property:

    using System;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media.Animation;
    
    static class ContentControlExtensions
    {
        public static readonly DependencyProperty ContentChangedAnimationProperty = DependencyProperty.RegisterAttached(
            "ContentChangedAnimation", typeof(Storyboard), typeof(ContentControlExtensions), new PropertyMetadata(default(Storyboard), ContentChangedAnimationPropertyChangedCallback));
    
        public static void SetContentChangedAnimation(DependencyObject element, Storyboard value)
        {
            element.SetValue(ContentChangedAnimationProperty, value);
        }
    
        public static Storyboard GetContentChangedAnimation(DependencyObject element)
        {
            return (Storyboard)element.GetValue(ContentChangedAnimationProperty);
        }
    
        private static void ContentChangedAnimationPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var contentControl = dependencyObject as ContentControl;
            if (contentControl == null)
                throw new Exception("Can only be applied to a ContentControl");
    
            var propertyDescriptor = DependencyPropertyDescriptor.FromProperty(ContentControl.ContentProperty,
                typeof (ContentControl));
    
            propertyDescriptor.RemoveValueChanged(contentControl, ContentChangedHandler);
            propertyDescriptor.AddValueChanged(contentControl, ContentChangedHandler);
        }
    
        private static void ContentChangedHandler(object sender, EventArgs eventArgs)
        {
            var animateObject = (FrameworkElement) sender;
            var storyboard = GetContentChangedAnimation(animateObject);
            storyboard.Begin(animateObject);
        }
    }
    

    and then in XAML:

            
                
                    
                        
                    
                
            
    

    It's much easier and shorter than a new control.

提交回复
热议问题