问题描述
我使用标准的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.
我在,并对其进行了一些修改。
I found the code in here and modified it a little.
这篇关于WPF ComboBox:在弹出窗口之外单击以抑制鼠标单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!