XAML - 在右键单击元素之上打开ContextMenu

时间:2018-06-15 15:14:23

标签: xaml contextmenu placement

我正在尝试在右键单击元素的顶部打开上下文菜单。但它只在鼠标点击位置打开。

<TextBlock Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" x:Name="testeTB" Text="Name:">
            <TextBlock.ContextMenu>
                <ContextMenu>
                    <ContextMenu.Style>
                        <Style TargetType="ContextMenu">
                            <Setter Property="Placement" Value="Top"></Setter>
                            <Setter Property="PlacementTarget" Value="{Binding ElementName=testeTB}"></Setter>
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="ContextMenu">
                                        <controls:PopupMenu>
                                            <controls:PopupMenu.Children>
                                                <wpf:ArbeitListBoxItem Content="Add Messages"></wpf:ArbeitListBoxItem>
                                                <wpf:ArbeitListBoxItem Content="Remove Messages"></wpf:ArbeitListBoxItem>
                                            </controls:PopupMenu.Children>
                                        </controls:PopupMenu>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </ContextMenu.Style>
                </ContextMenu>
            </TextBlock.ContextMenu>
        </TextBlock>
  

正如您在我的示例中所看到的,我尝试将Placement设置为&#34; Top&#34;和   还使用textblock元素名称设置PlacementTarget,但它   没有工作。

是否可以使用ContextMenu来完成?或者我应该使用弹出窗口?我更喜欢使用ContextMenu

1 个答案:

答案 0 :(得分:1)

尝试设置目标Control的ContextMenuService.Placement属性,这是一个XAML示例:

<Grid>
    <TextBlock
        Padding="10 5"
        Background="Lime"
        ContextMenuService.Placement="Right"
        Grid.Row="1"
        Grid.Column="0"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Text="Name:">
        <TextBlock.ContextMenu>
            <ContextMenu>
                <ContextMenu.Template>
                    <ControlTemplate>
                        <Border Background="Red">
                            <TextBlock Text="Context menu content..." Margin="20 15" />
                        </Border>
                    </ControlTemplate>
                </ContextMenu.Template>
            </ContextMenu>
        </TextBlock.ContextMenu>
    </TextBlock>
</Grid>