WPF:防止“已完成”事件在删除动画后触发
问题描述:
如何从WPF元素中删除正在运行的动画,以使其Completed事件不会触发?WPF:防止“已完成”事件在删除动画后触发
提供的解决方案为here和here删除动画的可见效果,但Completed事件在动画完成时仍会触发。
下面是一些代码,演示了我的问题(这是在一个标签,一个按钮的窗口背后的代码,和一个TextBox):
int _count = 0;
private void button1_Click(object sender, RoutedEventArgs e) {
myLabel.Content = "Starting animation: " + _count++;
// Cancel any already-running animations and return
// the label opacity to 1.0.
myLabel.BeginAnimation(Label.OpacityProperty, null);
myLabel.Opacity = 1.0;
// Create a new animation to fade out the label.
DoubleAnimation opacityAnim = new DoubleAnimation(1.0, 0.0, TimeSpan.FromSeconds(2), FillBehavior.Stop) {
BeginTime = TimeSpan.FromSeconds(3)
};
opacityAnim.Completed += (sndr, ev) => {
myTextbox.Text += Environment.NewLine + "Completed fired.";
};
// Start the countdown/animation.
myLabel.BeginAnimation(Label.OpacityProperty, opacityAnim);
}
如何删除的动画,使得它不会提高其Completed事件?
答
从已完成的情况下取消...这也意味着你必须从lambda来显式方法重写完成事件处理程序:
DoubleAnimation _opacityAnim; // Created somewhere else.
private void button1_Click(object sender, RoutedEventArgs e)
{
myLabel.Content = "Starting animation: " + _count++;
// Cancel any already-running animations and return
// the label opacity to 1.0.
_opacityAnim.Completed -= AnimationCompleted;
myLabel.BeginAnimation(Label.OpacityProperty, null);
myLabel.Opacity = 1.0;
// Create a new animation to fade out the label.
opacityAnim.Completed += AnimationCompleted;
// Start the countdown/animation.
myLabel.BeginAnimation(Label.OpacityProperty, opacityAnim);
}
private void AnimationCompleted(object sender, EventArgs e)
{
myTextbox.Text += Environment.NewLine + "Completed fired.";
}
迷人......我还以为这之前,但估计会依然火该事件是因为您马上添加了一个处理程序,并且它是相同的动画对象。然而,在实际测试它(新颖的概念)后,我发现它可以按照需要运行! (可能你能指出我对这是为什么的解释吗?)在代码中读取有点不直观,但我很高兴它可以工作。谢谢! – 2010-02-24 19:19:29