Search code examples
wpfalignmentcontextmenu

WPF Align contextmenu to the right-bottom corner of the button


I have a Button and a ContextMenu that belongs to the Button.
Here is the xaml:

<Button x:Name="ListBoxButton" Content="6" Style="{DynamicResource TabControlButton}">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="tst1"></MenuItem>
            <MenuItem Header="tst2"></MenuItem>
        </ContextMenu>
    </Button.ContextMenu>
</Button>

I want to align my ContextMenu exactly the same place like image #2 in this post
I want to use xaml to achieve it instead of code-behind.

I couldnt achieve it, I tried to play with the PlacementTarget, HorizontalOffset, VeritcalOffset and Placement properties of the ContextMenu but it didnt aligned as I want..


Solution

  • I think you should try something like this

    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Button HorizontalAlignment="Center" 
                    VerticalAlignment="Center" 
                    Height="20" Width="80" 
                    ContextMenuService.Placement="Left"                     
                    ContextMenuService.HorizontalOffset="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth}" 
                    ContextMenuService.VerticalOffset="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}">
                <Button.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Menu item 01"/>
                        <MenuItem Header="Menu item 02"/>
                    </ContextMenu>
                </Button.ContextMenu>
            </Button>
        </Grid>
    </Window>