Search code examples
c#wpfxamlcontextmenumenuitem

Overriding MenuItem ControlTemplate prevents the ContextMenu from closing when an item is clicked


I'm using WPF and overriding the ControlTemplate of a MenuItem like this:

<Button Content="Click Me" Margin="5">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem>
                <MenuItem.Template>
                    <ControlTemplate>
                        <Button Padding="0" BorderThickness="0" Background="Transparent" HorizontalAlignment="Left"
                                Command="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=DataContext.MenuItemCommand}">
                            <TextBlock Text="Item 1" Margin="5"/>
                        </Button>
                    </ControlTemplate>
                </MenuItem.Template>
            </MenuItem>
        </ContextMenu>
    </Button.ContextMenu>
</Button>

My context menu opens just fine and when I click the item it activates the button's command just fine, but the context menu does not close. Any suggestions on what I need to do to get the context menu to close after an item is clicked?


Solution

  • Remove the Button from the template and handle the Command of the MenuItem itself:

    <Button Content="Click Me" Margin="5">
        <Button.ContextMenu>
            <ContextMenu>
                <MenuItem Command="{Binding MenuItemCommand}">
                    <MenuItem.Template>
                        <ControlTemplate>
                            <TextBlock Text="Item 1" Margin="5"/>
                        </ControlTemplate>
                    </MenuItem.Template>
                </MenuItem>
            </ContextMenu>
        </Button.ContextMenu>
    </Button>