Search code examples
c#wpfcontextmenu

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?


Solution

  • 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();
    }