简体   繁体   中英

Can't get selected item context menu

here is my XAML and I am trying to get the value of the selected item in the Context Menu. I do not have the property of selected Item in my xaml. Is there another route i should go so that i am able to get the selected items from the context menu?

    <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>

If I understand you correctly, then this is a common problem in WPF. It is caused because the ContextMenu having its own visual tree, quite separate from the main visual tree. The consequence of that is that it has no access to the DataContext from the main visual tree. The solution is to utilise a Tag property to pass the DataContext .

Rather than explaining the whole story once again, I'd rather suggest that you read my answers to the Add context menu in datagrid, how to get the select Item value and Bind Context Menu inside ItemsControl? questions here on Stack Overflow, which both explain the same thing in different situations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM