WPF button with context menu, How to link the width of the context menu with the width of the button?

I have a simple button where I want the width of the context menu to be the same width as the button (I left-click the button, opening the context menu directly below the button).

<Button x:Name="btn" Content="Push Me">
    <Button.ContextMenu>
        <ContextMenu x:Name="cm">
            <MenuItem Header="One" />
            <MenuItem Header="Two" />
            <MenuItem Header="Three" />
        </ContextMenu>
    </Button.ContextMenu>
</Button>

I tried the following binding in the context menu itself and does not work

<ContextMenu x:Name="cm" Width="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Button}}, Path=ActualWidth}">

But I was able to get it to work in code

btn.LayoutUpdated += (s, e) => cm.Width = btn.ActualWidth;

My question is: is there a xaml binding that will give me this functionality?

+3
source share
2 answers

ContextMenuhas a property called PlacementTarget, which in this case will be Button, so you can try to use in the path forBinding

<ContextMenu x:Name="cm"
             Width="{Binding RelativeSource={RelativeSource Self},
                             Path=PlacementTarget.ActualWidth}">
+4
source

, ContextMenu NameScope. ContextMenu , , Popup, Popup null.

, MSDN, - NameScope, ContextMenu .

    NameScope.SetNameScope(this, new NameScope());

, , , ; .

+2

Source: https://habr.com/ru/post/1795566/


All Articles