简体   繁体   中英

How can I make a WPF ContextMenu automatically select the first item when it's opened?

I'm opening a ContextMenu when a user hits a short-cut key (by changing its IsOpen property to true). But when it opens, no item is selected. How can I make the first item be selected, so that the user doesn't have to press the down-arrow to reach it?

Try this:

<ListBox>
    <ListBoxItem Content="Item">
        <ListBoxItem.ContextMenu>
            <ContextMenu Opened="ContextMenu_Opened">
                <MenuItem Click="some_event" Header="Qwerty"/>
            </ContextMenu>
        </ListBoxItem.ContextMenu>
    </ListBoxItem>
</ListBox>

And in code-behind:

private void ContextMenu_Opened(object sender, RoutedEventArgs e)
{
    var contextMenu = sender as ContextMenu;
    (contextMenu.Items[0] as MenuItem).Focus();
}

I am not sure which control ( Datagrid, ListView or whatever) you are intending to select. However, the very first thing you need to check is that whether or not your control support KeyPress event. If it support, then try to attach handler for the KeyPress and write logic to check the required key and select item accordingly.

You can check a sample here which has the implementation on how to select data grid cell/row based on Enter key.

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