首页 > 解决方案 > WPF Button Style Trigger fired twice

问题描述

I'm currently working on a .NET 4.7.1 WPF application. I have an attached behavior on a button style on the IsPressed handler. I can reach the event handler.

However, when I click the button, the event gets somehow fired twice unfortunately.

My xaml looks like this:

<WrapPanel Orientation="Horizontal" HorizontalAlignment="Right">
    <Button Style="{StaticResource MySaveButton}">
        Save
    </Button>
</WrapPanel>

My style looks like this:

<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>

My behavior class looks like this:

 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
     }
}

Do you know how to fire the event only one time, using the style trigger?

Thank you very much!

标签: c#wpf

解决方案


The trigger is executing when the value of IsPressed changes (from true to false or the other way round). That means it is called when pressing and when releasing the button.

To check, which direction caused the trigger, you can check e.NewValue:

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

推荐阅读