如何确定ContextMenu在哪一侧打开?

时间:2011-11-06 16:17:30

标签: wpf

假设我有这个ContextMenu:

<Style x:Key="{x:Type ContextMenu}" TargetType="{x:Type ContextMenu}">
    <Setter Property="VerticalOffset" Value="-10"/>
    <Setter Property="HorizontalOffset" Value="-10"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ContextMenu}">
                <Border Background="Transparent">
                    <Border.Effect>
                        <DropShadowEffect BlurRadius="10" ShadowDepth="0" Opacity="0.5"/>
                    </Border.Effect>
                    <Border Margin="10" Style="{StaticResource MenuBorderStyle}">
                        <Grid x:Name="SubMenu" Grid.IsSharedSizeScope="True">
                            <!-- StackPanel holds children of the menu. This is set by IsItemsHost=True -->
                            <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle"/>
                        </Grid>
                    </Border>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

正如您所看到的,我将菜单的外观偏移了10个像素到顶部和左侧,使ContextMenu的左上角位于光标下方。

事实上,由于Border的10像素边距,整个控件应该比光标更左上角,因为它自己以阴影开始的控制。

而且,正如您可能已经猜到的那样,当上下文菜单不在光标的右下方(比如光标位于屏幕的底部或左侧)时,需要将偏移更改为相反的(通过X或Y或两者坐标)。

问题是如何通过xaml做到这一点?

(对不起我的英文)

1 个答案:

答案 0 :(得分:0)

尝试将Placement属性设置为AbsolutePoint。也请检查this,它可能对您有帮助。

相关问题