【问题标题】:Run Animation when Dependency Property Changes当依赖属性改变时运行动画
【发布时间】:2010-09-09 14:33:49
【问题描述】:

我创建了一个具有两个依赖属性的 UserControl:值和颜色。 UserControl 的颜色取决于 Value 属性。例如,如果 Value=0 Color=Blue,Value=0.5 Color=Red 等等。这是我使用绑定到 Fill 属性的自定义转换器实现的,如下所示:

<Ellipse Name="dotForeground" Stroke="Transparent" StrokeThickness="1" Fill="{Binding ElementName=control1, Converter={StaticResource colorConverter}, Path=Value}"/>

现在我需要的是,当 Value 属性从例如 0.0 更改为 0.5 时,因此也更改了 Color 属性,我想创建一个 ColorAnimation 以便它从以前的颜色淡化为新颜色。

我将不胜感激。

【问题讨论】:

    标签: wpf dependency-properties


    【解决方案1】:

    有几种方法可以做到这一点,一种是将画笔绑定到 Color 属性而不是使用转换器:

    <Ellipse Name="dotForeground" Stroke="Transparent" StrokeThickness="1">
        <Ellipse.Background>
             <SolidColorBrush Color="{Binding Color, ElementName=control1}" />
        </Ellipse.Background>
    </Ellipse>
    

    然后当值改变时在你的 UserControl 中启动一个 ColorAnimation。

    public Color Color
    {
        get { return (Color)GetValue(ColorProperty); }
        set { SetValue(ColorProperty, value); }
    }
    
    public static readonly DependencyProperty ColorProperty = DependencyProperty.Register("Color", typeof(Color), typeof(MyUserControl), new UIPropertyMetadata(Colors.Red));
    
    public double Value
    {
        get { return (double)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }
    
    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(MyUserControl), new UIPropertyMetadata(0.0,ValueChanged));
    
    private static void ValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var control = (MyUserControl)sender;
    
        var anim = new ColorAnimation { To = Color.FromRgb((byte)control.Value, 128, 60), FillBehavior = FillBehavior.HoldEnd};
        control.BeginAnimation(MyUserControl.ColorProperty, anim);
    }
    

    【讨论】:

      最近更新 更多