I have a rectangle in WPF defined in this way;
<Rectangle x:Name="redBrush" Width="20" Height="20" Fill="{Binding RectColor}" Stroke="Black" RadiusX="2" RadiusY="2">
I would like to animate the changing of the color from one to another.
I tried with something like this:
<Rectangle x:Name="redBrush" Width="20" Height="20" Fill="{Binding NewColor}" Stroke="Black" RadiusX="2" RadiusY="2">
<Rectangle.Triggers>
<EventTrigger RoutedEvent="Rectangle.MouseEnter">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="redBrush"
Storyboard.TargetProperty="(Rectangle.Fill).Color" To="{Binding NewColor}" Duration="0:0:3" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Rectangle.Triggers>
</Rectangle>
But I have two problems with this approach. Which RoutedEvent do I have to use? and the To= property in ColorAnimation does not work.
Could you help me? Thanks
Storyboards are freezable objects, you can't set their properties using bindings.
A workaround would be to generate a Storyboard every time Fill DP is changed:
private SolidColorBrush _rectColor;
public SolidColorBrush RectColor {
get {return _rectColor;}
set {
_rectColor = value;
_sbFillAnimation= CreateFillAnimationStoryboard(_rectColor);
_sbFillAnimation.Begin();
}
}
private Storyboard _sbFillAnimation;
private Storyboard CreateFillAnimationStoryboard(SolidColorBrush rectColor) {
Storyboard sb = new Storyboard() { Duration = TimeSpan.FromSeconds(3), BeginTime = TimeSpan.Zero};
ColorAnimation colAnim = new ColorAnimation();
colAnim.From = rectColor.Color;
colAnim.To = Colors.Gray;
colAnim.Duration = new Duration(TimeSpan.FromSeconds(3));
colAnim.AutoReverse = false;
sb.Children.Add(colAnim);
Storyboard.SetTarget(colAnim, redBrush);
Storyboard.SetTargetProperty(colAnim, new PropertyPath("Fill.Color"));
return sb;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.