如何使用AddHandler在WPF中的按钮上为LostKeyBoardFocusEvent添加事件处理程序

时间:2018-06-23 06:52:04

标签: c# wpf event-handling

我正在尝试封装一些按钮行为,其中之一是为事件“ LostKeyboardFocusEvent”添加事件处理程序,但是在运行时使用和SystemArgumentException出现“处理程序类型不匹配”错误:

AssociatedObject.AddHandler(Button.LostKeyboardFocusEvent, new DependencyPropertyChangedEventHandler(HandleButtonToolTip), true);

public static void HandleButtonToolTip(object sender, DependencyPropertyChangedEventArgs e)
        {
            //Get tooltip from sender.
            ToolTip tt = (ToolTip)(sender as Control).ToolTip;
            if ((sender as Control).IsKeyboardFocusWithin && !tt.IsOpen)
            {
                ShowButtonTooltip(sender);
            }
            else
            {
                ClearButtonTooltip();
            }
        }

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

更改

AssociatedObject.AddHandler(Button.LostKeyboardFocusEvent, new DependencyPropertyChangedEventHandler(HandleButtonToolTip), true);

AssociatedObject.AddHandler(Button.LostKeyboardFocusEvent, new RoutedEventHandler(HandleButtonToolTip), true);

然后改变

public static void HandleButtonToolTip(object sender, DependencyPropertyChangedEventArgs e)

public static void HandleButtonToolTip(object sender, RoutedEventArgs e)

答案 1 :(得分:0)

只需将处理程序的类型从DependencyPropertyChangedEventArgs更改为KeyboardFocusChangedEventHandler

AssociatedObject.AddHandler(Button.LostKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(HandleButtonToolTip), true);

...以及EventArgsKeyboardFocusChangedEventArgs的类型:

public static void HandleButtonToolTip(object sender, KeyboardFocusChangedEventArgs e)
...