当依赖属性改变时运行动画

3

我已经创建了一个带有两个依赖属性的用户控件:Value和Color。用户控件的颜色取决于Value属性。例如,如果Value=0,则Color=蓝色;如果Value=0.5,则Color=红色,以此类推。我使用一个自定义转换器来实现这一点,该转换器绑定到Fill属性,如下所示:

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

现在我需要的是,当Value属性从0.0变为0.5时,也就是Color属性发生变化时,我想创建一个ColorAnimation来使它从之前的颜色渐变到新的颜色。我会非常感激任何帮助。
1个回答

5
有几种方法可以实现这个,其中一种是将刷子绑定到颜色属性而不是使用转换器:
<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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接