views:

31

answers:

1

I have created a UserControl with two dependency properties: Value and Color. The Color of the UserControl is dependent on the Value property. For example if Value=0 Color=Blue, Value=0.5 Color=Red and so on. This I have achieved using a custom converter that is bound to the Fill property, like so:

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

Now what I need is that when the Value property changes from for example 0.0 to 0.5, which consequently also changes the Color property, I would want to create a ColorAnimation such that it fades from the previous color to the new color.

I would appreciate any help on this.

+1  A: 

There are a few methods to do this, one would be to bind a brush to the Color property instead of using a converter:

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

Then start a ColorAnimation in your UserControl when the Value changes.

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);
}
Kris
Thanks for the answer, worked perfect!