简体   繁体   中英

How to get the selected item from a context menu

I have a context menu which is binded to a list of items. When I click on an item, the command executes however I am having problems passing the selected item as a parameter, can anyone identify what I'm doing wrong?

I have tried passing {Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}} as the command parameter however it just gives me the whole list within the context menu and when. When I tried {Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}} no value was seen.

    <ContextMenu x:Key="SelectFileTab" ItemsSource="{Binding ContextMenuItems}" x:Name="contextmenu">
        <ContextMenu.ItemTemplate>
            <DataTemplate>
                <MenuItem Header="{Binding}">
                </MenuItem>
            </DataTemplate>
        </ContextMenu.ItemTemplate>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="PreviewMouseUp">
                <i:InvokeCommandAction Command="{Binding SelectedFileToAdd, Mode=OneWay}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>

    </ContextMenu>     

I really over complicated something quite simple, there was no need to use interaction.triggers issue to the command, all I needed to do was

<ContextMenu x:Key="SelectFileTab" ItemsSource="{Binding ContextMenuItems}" x:Name="contextmenu">
        <ContextMenu.ItemTemplate>
            <DataTemplate>
                 <MenuItem Header="{Binding}" Command="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.SelectedFileToAdd}"
                                       CommandParameter="{Binding RelativeSource={RelativeSource Self}}"/>
            </DataTemplate>
        </ContextMenu.ItemTemplate>
   </ContextMenu>

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