WPF Fade Animation

后端 未结 7 1355
余生分开走
余生分开走 2020-11-30 00:16

How would I make a control fade in/out when it becomes Visible.

Below is my failed attempt:



        
7条回答
  •  天涯浪人
    2020-11-30 01:07

    This is best done using a behavior

    class AnimatedVisibilityFadeBehavior : Behavior
       {
          public Duration AnimationDuration { get; set; }
          public Visibility InitialState { get; set; }
    
          DoubleAnimation m_animationOut;
          DoubleAnimation m_animationIn;
    
          protected override void OnAttached()
          {
             base.OnAttached();
    
             m_animationIn = new DoubleAnimation(1, AnimationDuration, FillBehavior.HoldEnd);
             m_animationOut = new DoubleAnimation(0, AnimationDuration, FillBehavior.HoldEnd);
             m_animationOut.Completed += (sender, args) =>
                {
                   AssociatedObject.SetCurrentValue(Border.VisibilityProperty, Visibility.Collapsed);
                };
    
             AssociatedObject.SetCurrentValue(Border.VisibilityProperty,
                                              InitialState == Visibility.Collapsed
                                                 ? Visibility.Collapsed
                                                 : Visibility.Visible);
    
             Binding.AddTargetUpdatedHandler(AssociatedObject, Updated);
          }
    
          private void Updated(object sender, DataTransferEventArgs e)
          {
             var value = (Visibility)AssociatedObject.GetValue(Border.VisibilityProperty);
             switch (value)
             {
                case Visibility.Collapsed:
                   AssociatedObject.SetCurrentValue(Border.VisibilityProperty, Visibility.Visible);
                   AssociatedObject.BeginAnimation(Border.OpacityProperty, m_animationOut);
                   break;
                case Visibility.Visible:
                   AssociatedObject.BeginAnimation(Border.OpacityProperty, m_animationIn);
                   break;
             }
          }
       }
    

    This is specifically being applied to a border - I haven't tried a user control but I expect the same applies.

    To use it, you need the Blend Interactivity namespace:

    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    

    And use this markup on the Border that you want the behavior on:

    
                    
    
    

    You'll need to add in the namespace for the behavior class too..

提交回复
热议问题