WPF组合框选择行为

时间:2013-04-11 20:42:50

标签: c# wpf combobox mouseevent

WPF ComboBox控件允许两种方法用鼠标更改选择。

  • 用鼠标单击向下/向上,弹出窗口,然后单击要选择的项目。

  • 您点击并按住。出现弹出窗口,将鼠标悬停在要选择的项目上并释放鼠标按钮。选择MouseUp事件时鼠标所在的项目。

有没有办法消除behavior #2?即让它们执行2次完全向下/向上点击以更改选择?

1 个答案:

答案 0 :(得分:2)

它可能并不漂亮,但结合一些事件似乎可以做你想要的事情:

private bool _comboMouseDown = false;
private bool _comboSelectionDisabled = false;

private void ComboBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    _comboMouseDown = true;
}

private void ComboBox_DropDownOpened(object sender, EventArgs e)
{
    if (_comboMouseDown)
    {
        //Don't enable selection until the user releases the mouse button:
        _comboSelectionDisabled = true;
    }
}

private void ComboBox_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
    if (_comboSelectionDisabled)
    {
        //Stop the accompanying "MouseUp" event (which would select an item) from firing:
        e.Handled = true;

        _comboSelectionDisabled = false;
    }

    _comboMouseDown = false;
}

1)仍然正常工作

2)点击并按住仍会打开弹出窗口,但您需要释放并再次单击以选择项目。