简体   繁体   中英

WPF Combobox selection behavior

WPF ComboBox controls allow two ways to change the selection with the mouse.

  • You click down/up with the mouse, the popup appears, you then click on the item you want to select.

  • You click down and hold. The popup appears, you mouse over the item you want to select and release the mouse button. The item your mouse is over at the time of the MouseUp event is selected.

Is there a way to eliminate behavior #2 ? Ie make them perform 2 full down/up clicks to change the selection?

It may not not pretty, but combining a few events seems to do what you're after:

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) Still works as normal

2) Click-and-hold still opens the popup, but you need to release and click again to select an item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM