如何从 WPF 元素中删除正在运行的动画,使其不会触发其 Completed 事件?
提出的解决方案here和 here删除动画的可见效果,但 Completed 事件仍会在动画完成时触发。
这里有一些代码演示了我的问题(它位于带有标签、按钮和文本框的窗口后面的代码中):
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 事件?
最佳答案
取消订阅 Completed 事件...这也意味着您必须将 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.";
}
关于WPF:删除动画后防止触发 "Completed"事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2327929/