【问题标题】:EventTrigger listening to Loaded is triggered twice?监听Loaded的EventTrigger被触发了两次?
【发布时间】:2015-10-11 08:45:18
【问题描述】:

首先,我不确定它是否真的被触发了两次。如果在后面的代码中测试,Loaded 事件只会触发一次(甚至尝试使用接受第三个参数 handledEventsToo 的 AddHandler)。不过看起来很有可能。我在 XAML 中有一个 Storyboard 设置,并且在引发 Loaded 时应该只运行一次。但它似乎开始了 2 次,尤其是第二次是在显示窗口之后。

我知道这是因为我在情节提要内的 DoubleAnimation 上使用了一个附加属性。此附加属性具有 1 个 propertyChangedCallback 处理程序。然而,这个处理程序被触发两次,使用相同的 e.NewValue 值(来自参数)。它不应该像那样被触发两次。我可以确定目标(动画)并设置一些附加标志来标记已对其进行的操作,以防止两次触发的问题,但这也会阻止其他实际触发(不是来自Loaded)。然而,DoubleAnimation 本身是为每个触发器新创建的(因此我也无法在其上标记任何标志,因为每次触发 propertyChangedCallback 都是另一个 DoubleAnimation 的另一个时间,无法标记和阻止执行)。

这里是代码,只是简单测试一下:

public class TestOwner {
    public static readonly DependencyProperty TestProperty =
        DependencyProperty.RegisterAttached("Test", typeof(bool), typeof(TestOwner), new PropertyMetadata(testChanged));
    public static bool GetTest(DependencyObject o)
    {
        return (bool) o.GetValue(TestProperty);
    }
    public static void SetTest(DependencyObject o, bool value)
    {
        o.SetValue(TestProperty, value);
    }
    static private void testChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    { //Mark some break point here and run it, you'll see it's stopped 
      //here twice, the second time is right after the window is shown.
      //...
    }
}

XAML

<FrameworkElement>
        <FrameworkElement.Triggers>
            <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation From="20000" To="0" 
                                        Duration="00:00:20" 
                                        Storyboard.TargetName="someName"
                                         local:TestOwner.Test="True"/>

                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </FrameworkElement.Triggers>
</FrameworkElement>

我想避免这种两次触发以及理解为什么会这样。

【问题讨论】:

    标签: c# wpf animation storyboard eventtrigger


    【解决方案1】:

    好吧,事实上EventTrigger 只被触发一次。我在问题中所说的几乎都是错误的看法。我发现Storyboard 看起来像克隆了DoubleAnimation,这实际上甚至克隆了附加属性,导致两次进入 propertyChanged 回调处理程序。第一次是为原来的DoubleAnimation。第二次是克隆的DoubleAnimation,它可能实际上是在Loaded被提升时被克隆并运行的,所以它发生在我之前所说的窗口显示之后。

    至少现在我理解了这个问题,而且更多的调试告诉我,那种 2 次进入处理程序不会影响任何严重的问题。所以这个问题对我来说似乎已经解决了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2015-11-22
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多