WPF ComboBox:在弹出窗口外单击抑制鼠标单击 [英] WPF ComboBox: click outside of popup suppress mouse click

查看:30
本文介绍了WPF ComboBox:在弹出窗口外单击抑制鼠标单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用标准的 WPF ComboBox 控件.当弹出窗口被打开并且用户点击外面的某个地方时,弹出窗口被关闭.但是如果窗口上有按钮并且用户单击它(弹出窗口仍然打开),则不会执行按钮的单击处理程序.弹出窗口已关闭,但用户必须在按钮上再单击一次才能在其上引发单击事件.

I use a standard WPF ComboBox control. When popup is opened and user clicks somewhere outside, popup is closed. But if there is button on the window and user clicks on it (with popup still opened), button's click handler is not executed. Popup is closed, but user has to click one more time on the button to raise click event on it.

我知道这是该控件的标准行为.你有什么想法如何绕过这种行为吗?谢谢!

I know that is standard behavior for this control. Have you any ideas how to bypass this behavior? Thanks!

推荐答案

您可以为 ComboBox DropDownClosed 创建一个事件,并使用 hittest 函数查找用户单击的其他控件.

You can create an event for ComboBox DropDownClosed and with the hittestfunction, find the other control that the user has clicked.

private void ComboBox_DropDownClosed(object sender, EventArgs e)
{
    Point m = Mouse.GetPosition(this);
    VisualTreeHelper.HitTest(this, this.FilterCallback, this.ResultCallback, new PointHitTestParameters(m));
}

private HitTestFilterBehavior FilterCallback(DependencyObject o)
{
    var c = o as Control;
    if ((c != null) && !(o is MainWindow))
    {
        if (c.Focusable)
        {
            if (c is ComboBox)
            {
                (c as ComboBox).IsDropDownOpen = true;
            }
            else
            {
                var mouseDevice = Mouse.PrimaryDevice;
                var mouseButtonEventArgs = new MouseButtonEventArgs(mouseDevice, 0, MouseButton.Left)
                {
                    RoutedEvent = Mouse.MouseDownEvent,
                    Source = c
                };
                c.RaiseEvent(mouseButtonEventArgs);
            }

            return HitTestFilterBehavior.Stop;
        }
    }
    return HitTestFilterBehavior.Continue;
}

private HitTestResultBehavior ResultCallback(HitTestResult r)
{
    return HitTestResultBehavior.Continue;
}

然后在找到该控件后的 FilterCallback 函数中,在该控件上引发鼠标按下事件.

Then in the FilterCallback function after finding that control, raise the mouse down event on that control.

我发现了 raise 事件,在组合框上不起作用,因此单击该事件时,我只需将 IsDropDownOpen 设置为 true.

I found the raise event, does not work on comboboxes so for clicking that, I simply set the IsDropDownOpen to true.

我在 here 并稍作修改.

这篇关于WPF ComboBox:在弹出窗口外单击抑制鼠标单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆