c# – 从动画完成事件中获取UIElement
作者:互联网
从我的代码隐藏开始,我想在特定的UIElement上开始动画,当动画结束时,我想对该UIElement进行一些其他的处理.我无法弄清楚如何将我作为动画完成事件的发送者接收的AnimationClock对象转换为执行动画的UIElement对象.
这是我用来构建和启动动画的代码:
DoubleAnimation FadeOutAnim = new DoubleAnimation(1, 0, TimeSpan.FromSeconds(.5));
FadeOutAnim.Completed += new EventHandler(FadeOutAnim_Completed);
UIElement element = lstMessages.ItemContainerGenerator.ContainerFromItem(sender) as UIElement;
if(element != null)
element.BeginAnimation(UIElement.OpacityProperty, FadeOutAnim);
这是我完成的活动,我希望再次访问UIElement.
void FadeOutAnim_Completed(object sender, EventArgs e)
{
UIElement animation = sender; //This is an AnimationClock and I can't seem to figure out how to get my UIElement back.
}
任何帮助将不胜感激.
解决方法:
如果处理程序是无用的(我找不到恢复动画元素的方法),你可以只引发另一个包含该信息的事件:
private event EventHandler FadeAnimationCompleted;
private void OnFadeAnimationCompleted(object sender)
{
var handler = FadeAnimationCompleted;
if (handler != null)
handler(sender, null);
}
FadeAnimationCompleted += new EventHandler(This_FadeAnimationCompleted);
FadeOutAnim.Completed += (s, _) => OnAnimationCompleted(element);
void This_FadeAnimationCompleted(object sender, EventArgs e)
{
//Sender is the UIElement
}
更容易的是在委托中进行直接的方法调用:
FadeOutAnim.Completed += (s, _) => FadeAnimationCompleted(element);
void FadeAnimationCompleted(UIElement element)
{
//Meaningful code goes here.
}
标签:c,casting,animation,wpf,uielement 来源: https://codeday.me/bug/20190531/1187651.html