繁体   English   中英

WPF按钮样式触发器触发两次

[英]WPF Button Style Trigger fired twice

我目前正在开发.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
     }
}

您是否知道使用样式触发器仅触发一次事件?

非常感谢你!

IsPressed的值更改(从truefalse或相反)时,将执行触发器。 这意味着在按下和释放按钮时会调用它。

要检查是哪个方向引起了触发,可以检查e.NewValue

private static void OnSave(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (e.NewValue)
    {
        // changed from unpressed to pressed
    }
}

暂无
暂无

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

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