WPF MVVM Property Change Animation

前端 未结 4 1008
盖世英雄少女心
盖世英雄少女心 2020-12-13 22:30

I am looking for a clean way to start an animation that will have dynamic values. Basically I want to do an animation where an element changes width based on the data of an

4条回答
  •  天命终不由人
    2020-12-13 23:10

    Since properties modified by animation cannot be set outside the animation 'context', I came up with a code solution since I could not do the same in XAML effectively.

    private void UserControl_IsVisibleChanged(object sender, 
        DependencyPropertyChangedEventArgs e)
    {
        if (this.Visibility == Visibility.Visible)
        {
            DoubleAnimation fadeIn = new DoubleAnimation();
            fadeIn.From = 1d;
            fadeIn.To = 1d;
            fadeIn.Duration = new Duration(new TimeSpan(0, 0, 0));
    
            DoubleAnimation fade = new DoubleAnimation();
            fade.From = 1d;
            fade.To = 0d;
            fade.BeginTime = TimeSpan.FromSeconds(5);
            fade.Duration = new Duration(new TimeSpan(0, 0, 1));
    
            NameScope.SetNameScope(this, new NameScope());
            this.RegisterName(this.Name, this);
    
            Storyboard.SetTargetName(fadeIn, this.Name);
            Storyboard.SetTargetProperty(fadeIn, new PropertyPath
                (UIElement.OpacityProperty));
    
            Storyboard.SetTargetName(fade, this.Name);
            Storyboard.SetTargetProperty(fade, new PropertyPath
                (UIElement.OpacityProperty));
    
            Storyboard sb = new Storyboard();
            sb.Children.Add(fadeIn);
            sb.Children.Add(fade);
    
            sb.Completed += new EventHandler(sb_Completed);
            sb.Begin(this);
        }
    }
    
    void sb_Completed(object sender, EventArgs e)
    {
        this.Visibility = Visibility.Hidden;
    }
    

提交回复
热议问题