0

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>
Crono
  • 10,211
  • 6
  • 43
  • 75
Robert
  • 646
  • 4
  • 12
  • 37
  • ContextMenus are not part of the same VisualTree as the rest of your UI controls. If you want to use a binding to pull data into your ContextMenu, you need to use the `PlacementTarget` property to find the control the ContextMenu is attached to, and go from there. See [here](http://stackoverflow.com/a/5236744/302677) for an example. – Rachel Feb 19 '14 at 21:56

1 Answers1

1

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.

Community
  • 1
  • 1
Sheridan
  • 68,826
  • 24
  • 143
  • 183