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

Wpf 当依赖项属性更改时运行动画,wpf,dependency-properties,Wpf,Dependency Properties,我创建了一个UserControl,它有两个依赖属性:Value和Color。UserControl的颜色取决于Value属性。例如,如果值=0颜色=蓝色,值=0.5颜色=红色,依此类推。这是我使用绑定到Fill属性的自定义转换器实现的,如下所示: <Ellipse Name="dotForeground" Stroke="Transparent" StrokeThickness="1" Fill="{Binding ElementName=control1, Converter={Sta

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

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

现在我需要的是,当Value属性从例如0.0更改为0.5时,这也会更改Color属性,我希望创建一个ColorAnimation,使其从以前的颜色淡入新颜色


如果您能在这方面提供帮助,我将不胜感激。

有几种方法可以做到这一点,其中之一是将笔刷绑定到颜色属性,而不是使用转换器:

<Ellipse Name="dotForeground" Stroke="Transparent" StrokeThickness="1">
    <Ellipse.Background>
         <SolidColorBrush Color="{Binding Color, ElementName=control1}" />
    </Ellipse.Background>
</Ellipse>
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);
}