依赖项属性更改时运行动画

时间:2010-09-09 14:33:50

标签: wpf dependency-properties

我创建了一个具有两个依赖项属性的UserControl:Value和Color。 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,使其从之前的颜色渐变为新颜色。 / p>

我将不胜感激。

1 个答案:

答案 0 :(得分:5)

有几种方法可以做到这一点,一种方法是将画笔绑定到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);
}