Setting a WPF ContextMenu's PlacementTarget property in XAML?

前端 未结 3 1423
失恋的感觉
失恋的感觉 2020-12-09 03:48
相关标签:
3条回答
  • 2020-12-09 04:36

    You should be setting the ContextMenuService.Placement attached property on the button, as stated in the remarks in the documentation for ContextMenu.Placement.

    <Button Name="btnFoo" Content="Foo" ContextMenuService.Placement="Bottom">
        <Button.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Bar" />
            </ContextMenu>
        </Button.ContextMenu>
    </Button>
    
    0 讨论(0)
  • 2020-12-09 04:39

    Have you tried this:

    <Button Name="btnFoo" Content="Foo">
        <Button.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Bar" />
            </ContextMenu>
        </Button.ContextMenu>
    </Button>
    

    This will make the ContextMenu open where you right clicked your mouse (on the button). Which I think might be your desired location right?

    --- EDIT --- In that case use this:

    <Button Name="btnFoo" Content="Foo" ContextMenuOpening="ContextMenu_ContextMenuOpening">
        <Button.ContextMenu>
            <ContextMenu Placement="Bottom">
                <MenuItem Header="Bar" />
            </ContextMenu>
        </Button.ContextMenu>
    </Button>
    

    And in code behind:

    private void ContextMenu_ContextMenuOpening(object sender, ContextMenuEventArgs e)
    {
        // Get the button and check for nulls
        Button button = sender as Button;
        if (button == null || button.ContextMenu == null)
            return;
        // Set the placement target of the ContextMenu to the button
        button.ContextMenu.PlacementTarget = button;
        // Open the ContextMenu
        button.ContextMenu.IsOpen = true;
        e.Handled = true;
    }
    

    You can reuse the method for multiple buttons and ContextMenu's..

    0 讨论(0)
  • 2020-12-09 04:52

    You could use a <Menu />, styled as a Button and avoid the hassle with the ContextMenuService.

    0 讨论(0)
提交回复
热议问题