【发布时间】: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