无法获取所选项目上下文菜单

时间:2014-02-19 21:28:25

标签: c# wpf

这是我的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>

1 个答案:

答案 0 :(得分:1)

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

我不想再次解释整个故事,而是建议您在Stack Overflow上阅读我对Add context menu in datagrid, how to get the select Item valueBind Context Menu inside ItemsControl?问题的答案,这些问题在不同情况下都解释了同样的事情。