【问题标题】:Can't get selected item context menu无法获取所选项目上下文菜单
【发布时间】:2014-02-19 21:28:24
【问题描述】:

这是我的 XAML,我正在尝试获取上下文菜单中所选项目的值。我的 xaml 中没有选定项目的属性。我应该走另一条路线,以便能够从上下文菜单中获取所选项目吗?

    <Style x:Key="ContextMenuItemStyle" TargetType="{x:Type MenuItem}">
        <Setter Property="ItemsSource" Value="{Binding SubItem}"/>

            <TextBox Grid.ColumnSpan="8" Grid.RowSpan="2" x:Name="tbRadStudyType" Text="Click to set Care Plan Type" IsReadOnly="True" Margin="2" TextWrapping="Wrap">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="PreviewMouseDown">
                        <i:InvokeCommandAction Command="{Binding PreviewMouseDownCommand}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>

                <TextBox.ContextMenu>
                    <ContextMenu ItemsSource="{Binding PlanMainList}" 
                                 ItemContainerStyle="{StaticResource ContextMenuItemStyle}">

                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="PreviewMouseDown">
                                <i:InvokeCommandAction Command="{Binding PreviewMouseDownCommand}" />
                            </i:EventTrigger>
                        </i:Interaction.Triggers>

                        <ContextMenu.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Term}" />
                            </DataTemplate>
                        </ContextMenu.ItemTemplate>
                    </ContextMenu>
                </TextBox.ContextMenu>                     
            </TextBox>

【问题讨论】:

  • ContextMenus 与其他 UI 控件不属于同一 VisualTree。如果您想使用绑定将数据拉入您的 ContextMenu,您需要使用PlacementTarget 属性找到 ContextMenu 附加到的控件,然后从那里开始。有关示例,请参见 here

标签: c# wpf


【解决方案1】:

如果我理解正确,那么这是 WPF 中的常见问题。这是因为ContextMenu 有自己的视觉树,与主视觉树完全分开。这样做的结果是它无法从主视觉树访问DataContext。解决方案是利用Tag 属性来传递DataContext

与其再次解释整个故事,我更愿意建议您阅读我在 Stack Overflow 上对 Add context menu in datagrid, how to get the select Item valueBind Context Menu inside ItemsControl? 问题的回答,这两个问题在不同情况下都解释了相同的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多