【发布时间】:2016-09-22 15:08:03
【问题描述】:
每次都有一个蓝色矩形从窗口的左侧向右移动不同的距离。
无论是单击矩形还是动画完成,矩形都会从左侧重新开始移动。
如果点击矩形,它的颜色会变成绿色,持续时间为0.3s。
但是 MouseDown 事件似乎没有启动 ColorAnimation 并且矩形的移动距离/持续时间也不正确。
private int i;
private Storyboard hitTargetStoryboard;
private List<double> disList;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
disList = new List<double>{.......}; // init with a list of values.
/* Create a rectangle */
Rectangle rect = new Rectangle();
this.RegisterName("rect", rect);
rect.Height = this.ActualHeight;
rect.Width = 50;
Canvas.SetTop(rect, 0);
Canvas.SetLeft(rect, 0);
/* Fill rect with a solid brush */
SolidColorBrush targetRectBrush = new SolidColorBrush(Colors.Blue);
this.RegisterName("targetRectBrush", targetRectBrush);
rect.Fill = targetRectBrush;
/* Add mouse down event */
rect.MouseDown += Rect_MouseDown;
/* Add rect to Canvas */
myCanvas.Children.Add(rect);
/* Create ColorAnimation to change color smoothly */
ColorAnimation hitCA = new ColorAnimation();
hitCA.To = Colors.Green;
hitCA.Duration = TimeSpan.FromSeconds(0.3);
hitCA.Completed += HitCA_Completed;
/* Create storyboard and add ColorAnimation to it */
hitTargetStoryboard = new Storyboard();
Storyboard.SetTargetName(hitCA, "targetRectBrush");
Storyboard.SetTargetProperty(hitCA, new PropertyPath(SolidColorBrush.ColorProperty));
hitTargetStoryboard.Children.Add(hitCA);
i = 0;
TargetAnimation(i);
}
/* move the rect from 0--disList[i] */
private void TargetAnimation(int i)
{
(this.FindName("rect") as Rectangle).Fill = Brushes.Blue;
DoubleAnimation da = new DoubleAnimation();
da.From = 0;
da.To = disList[i];
da.Duration = TimeSpan.FromSeconds(5);
Storyboard.SetTargetName(da, "rect");
Storyboard.SetTargetProperty(da, new PropertyPath(Canvas.LeftProperty));
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(da);
storyboard.Completed += Storyboard_Completed;
storyboard.Begin(this);
}
/* If rect clicked, it will change color to green */
private void Rect_MouseDown(object sender, MouseButtonEventArgs e)
{
hitTargetStoryboard.Begin(this);
}
/* After color changed, rect starts over */
private void HitCA_Completed(object sender, EventArgs e)
{
TargetAnimation(++i);
}
/* If rect not clicked, it will start over */
private void Storyboard_Completed(object sender, EventArgs e)
{
TargetAnimation(++i);
}
更新:
删除:(this.FindName("rect") as Rectangle).Fill = Brushes.Blue;
添加:hitCA.From = Colors.Blue;
ColorAnimation 效果很好。
静止:
如果我删除Storyboard_Completed 或HitCA_Completed,rect 的移动顺利。而如果我两者都有,那么运动就会走错路。
更新 2:
编辑:storyboard.Begin(this, true) 在TargetAnimation(int i) 方法中。
在HitCA_Completed 方法中添加:stroyboard.Stop(this)。
如果不将isControallable设置为true,故事板将无法控制。
已解决
【问题讨论】:
-
它是从Window 派生的MainWindow 类的一部分。矩形是 System.Windows.Shapes.Rectangle。 @PetterHesselberg
标签: c# wpf animation mousedown coloranimation