简体   繁体   中英

All WPF context menus do not seem to handle highlighting items properly when a modifier key is held down

It happens in all my WPF applications and Visual Studio 2019 (which is definitely WPF based) also exhibits this strange behavior:

Simply right click an item in the solution explorer while holding, say, the Control key and you should notice that the items highlighting will intermittently work if you keep holding the Control modifier.

At first I presumed that the grids and lists controls were still catching the modifier keys for the items selection but this issue also occurs with a context menu on a simple control like a standard button.

Is there a way to fix this glitch?


Here is a gif with wpf application context menu in action. First I move mouse normally, then with Ctrl hold down:

As you can see it glitch (is not highlighting menu items).

MenuItem sets an internal flag when a key is pressed that stops mouse events from being registered temporarily, regardless of if it is actually a key that performs navigation. This reflects the behavior that I see, which is that the selection stutters when I hold down any key, not only modifiers. https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/windows/Controls/MenuItem.cs,2049

Since it's private there is no proper way to fix this. However if it is critical you can add a KeyDown handler for all your MenuItem s and then change it with reflection

var menu = sender as MenuItem;
if (menu != null)
{
    var parent = ItemsControl.ItemsControlFromItemContainer(menu);
    MethodInfo setBoolField = menu.GetType().GetMethod("SetBoolField",
        BindingFlags.NonPublic | BindingFlags.Static);
    setBoolField.Invoke(this, new object[] { parent, 0x04, false });
}

If you want you can first check if the key was a navigation key to retain the desired behavior.

I would personally consider this a bug in WPF.

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