我目前正在开发一个 .NET 4.7.1 WPF 应用程序。我在 IsPressed 处理程序的按钮样式上有附加行为。我可以到达事件处理程序。但是,当我单击按钮时,不幸的是,该事件以某种方式被触发了两次。我的 xml 看起来像这样:<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 }}你知道如何使用样式触发器只触发一次事件吗?
1 回答
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
当值发生IsPressed变化(从true到false或相反)时,触发器正在执行。这意味着它在按下和释放按钮时被调用。
要检查哪个方向导致触发,您可以检查e.NewValue:
private static void OnSave(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue)
{
// changed from unpressed to pressed
}
}
- 1 回答
- 0 关注
- 131 浏览
添加回答
举报
0/150
提交
取消