通过Behavior <frameworkelement>中的PreviewMouseLeftButtonDown处理ClickEvent

时间:2017-07-05 15:04:36

标签: c# wpf events mouseevent behavior

我有一个Behavior<FrameworkElement>,我在其中注册PreviewKeyDownPreviewMouseLeftButtonDown。我已将此Behavior附加到MenuItem上。现在,当我点击MenuItem时,有时仍会调用ClickEvent,有时则不会。这就像一个计时问题。您对如何解决此问题有任何建议并停止调用event吗?

protected override void OnAttached()
{
    base.OnAttached();
    AssociatedObject.PreviewKeyDown += _OnPreviewKeyDown;
    AssociatedObject.PreviewMouseLeftButtonDown += _OnPreviewMouseLeftButtonDown;
}

private void _OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
    if (!_HasAccess())
        mouseButtonEventArgs.Handled = true;
}

private void _OnPreviewKeyDown(object sender, KeyEventArgs keyEventArgs)
{
    if (!_HasAccess())
        keyEventArgs.Handled = true;
}

1 个答案:

答案 0 :(得分:0)

我还必须订阅AssociatedObject.PreviewMouseLeftButtonUp并设置handled = true。现在我得到了理想的行为!