c# - 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!
解决方案
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
}
}
推荐阅读
- facebook - wit.ai 与 facebook Messenger 的集成问题
- dart - 在打开键盘时,内容不会被向上推
- maven - 使用 Java 11 运行 Spring Boot 应用程序时出现 java.lang.StackOverflowError
- codeigniter - codeigniter 中的分页页面未正确突出显示
- mobile - 在设备中调用 ionic 3 API 的正确方法
- go - beego二进制安装了一个荒谬的路径,'bee new'命令不起作用
- angular - 如果结果包含部分文本,则尝试隐藏变量
- java - 套接字关闭异常和EOF异常
- bash - 如何从 shell 脚本中的测试输出中搜索“ERROR”字符串?
- sql - 插入语句中的 SQL 选择