【问题标题】:WPF Button Style Trigger fired twiceWPF 按钮样式触发器触发两次
【发布时间】: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 的值(仅在按下按钮时为真,而不是在释放按钮时为真)
  • 是的,确实 - 非常感谢!
  • 我会将其作为答案发布,以便您关闭问题

标签: c# wpf


【解决方案1】:

IsPressed 的值发生变化(从true 变为false 或相反)时,触发器正在执行。 这意味着它在按下和释放按钮时被调用。

要查看是哪个方向触发的,可以查看e.NewValue

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

【讨论】:

    猜你喜欢
    • 2012-06-02
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 2022-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多