【发布时间】:2019-03-07 17:12:28
【问题描述】:
我目前正在开发一个 .NET 4.7.1 WPF 应用程序。我在 IsPressed 处理程序的按钮样式上有附加行为。我可以到达事件处理程序。
但是,当我单击按钮时,不幸的是,事件以某种方式触发了两次。
我的 xaml 看起来像这样:
<WrapPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button Style="{StaticResource MySaveButton}">
Save
</Button>
</WrapPanel>
我的风格是这样的:
<Style TargetType="Button" BasedOn="{StaticResource SomeOtherBaseStyle}" x:Key="MySaveButton">
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="localBehaviors:MyBehavior.Save" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
我的行为类如下所示:
public class MyBehavior : Behavior<UIElement>
{
public static readonly DependencyProperty SaveProperty =
DependencyProperty.RegisterAttached("Save", typeof(bool), typeof(MyBehavior), new UIPropertyMetadata(OnSave));
public static bool GetSave(DependencyObject obj) => (bool)obj.GetValue(SaveProperty);
public static void SetSave(DependencyObject obj, bool value) => obj.SetValue(SaveProperty, value);
private static void OnSave(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// gets triggered twice when I click the button. Should be raised only once.
// ... some logic
}
}
你知道如何使用样式触发器只触发一次事件吗?
非常感谢!
【问题讨论】:
-
我猜它会在按下和释放按钮时被调用。要找出您有两种情况中的哪一种,您可以在
OnSave方法中检查e.NewValue的值(仅在按下按钮时为真,而不是在释放按钮时为真) -
是的,确实 - 非常感谢!
-
我会将其作为答案发布,以便您关闭问题