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

柔情痞子 提交于 2019-12-24 17:15:39

问题


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..


回答1:


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>


来源:https://stackoverflow.com/questions/19674228/wpf-align-contextmenu-to-the-right-bottom-corner-of-the-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!