【问题标题】:ContextMenu not appearing when clicking on 'empty space' within StackPanel单击 StackPanel 中的“空白空间”时未出现 ContextMenu
【发布时间】:2011-09-12 16:38:15
【问题描述】:

我有一个 HierarchicalDataTemplate,它在水平 StackPanel 中包含一些简单的项目。 上下文菜单也分配给根 StackPanel 容器:

<HierarchicalDataTemplate DataType="{x:Type data:GroupViewModel}"
                              ItemsSource="{Binding Path=Children}">
    <StackPanel Orientation="Horizontal" Margin="2" ContextMenuOpening="groupContextMenuOpening">
        <StackPanel.ContextMenu>
            <StaticResource ResourceKey="groupContextMenu" />
        </StackPanel.ContextMenu>

        <Rectangle Width="16" Height="15" Fill="{Binding Converter={StaticResource HierarchyLevelConverter}}" Margin="0 0 3 0" Cursor="Hand" >
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseLeftButtonDown" >
                    <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding SetCurrent}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>                
        </Rectangle>
        <Image Width="16" Height="15" Source="{Binding Path=GroupState, Converter={StaticResource GroupStateConverter}}" Cursor="Hand" Margin="0 0 3 0">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseLeftButtonDown" >
                    <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding ToggleGroupState}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Image>
    </StackPanel>
</HierarchicalDataTemplate>

宿主 TreeView 也使用 ContextMenu。 这个想法是,如果您右键单击 TreeView 中的某个项目,您将获得它的 ContextMenu。 如果您在树视图中的空白处单击鼠标右键,您将获得带有较少选项的“默认”上下文菜单。

除了一个奇怪的问题外,这一切都有效。 如您所见,水平 StackPanel 在图像之间留有边距。如果我右键单击项目之间的那个空间,就会出现 TreeView 上下文菜单。我希望在我的 HierarchicalDataTemplate 中定义的 ContextMenu 会在我右键单击 StackPanel 本身时弹出。

我发现如果我为 StackPanel 分配背景颜色,它就会起作用,但如果可能的话,我宁愿避免这种情况。

有什么想法吗?

【问题讨论】:

    标签: wpf xaml stackpanel


    【解决方案1】:

    StackPanelBackground 设置为Transparent 以使其在那些空白区域中命中测试。

    【讨论】:

    • 刚刚设法使用祖先绑定来使用与父级相同的背景。那是我本来可以忍受的。但我更喜欢你的建议。谢谢!
    • 你能解释一下当你设置为透明时幕后发生了什么
    • @SujithJagini:我不能,我只知道系统的行为。
    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2017-01-04
    相关资源
    最近更新 更多