繁体   English   中英

WPF:如何从事件处理程序中获取触发动画的控件的名称?

[英]WPF: How to get the name of the control that fired an animation, from within the event handler?

我正在使用 DoubleAnimation 在 XAML 中设置淡出动画。 它淡出一Frame ,然后在Completed后触发Completed事件。

我想从事件处理程序中获取触发动画的控件的名称,但我找不到方法。

XAML

<Button x:Name="btnNavMessages">
    <!-- Some Text-->
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.PreviewMouseDown">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation
                        Storyboard.TargetName="MichaelFrame"
                        Storyboard.TargetProperty="Opacity"
                        To="0"
                        Duration="0:0:1" 
                        Completed="DoubleAnimation_Completed" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Button.Triggers>
</Button>

代码隐藏

private void DoubleAnimation_Completed(object sender, EventArgs e)
{
    // How to find out which control fired the animation? e.g. "btnNavMessages"
    // Tried `Button btn = sender as Button;`
    // But `sender.ToString()` is `System.Windows.Media.Animation.AnimationClock`, not `Button`
}

任何帮助,将不胜感激。 谢谢。


编辑:

我已经尝试了以下代码,它可以工作,但它确实不优雅。 除了优雅之外,它还有一个恼人的错误 - 当我单击按钮并在动画期间按下选项卡时,焦点会发生变化并且应用程序停止。 还有其他解决方案吗?

Button btn = FocusManager.GetFocusedElement(this) as Button;

这可能是一个解决方案?

XAML 删除

Completed="DoubleAnimation_Completed"

调整

<Button x:Name="btnNavMessages" Click="btnNavMessages_Click"  >

代码隐藏

private void btnNavMessages_Click(object sender, RoutedEventArgs e)
{
    var btn = sender as Button;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM