简体   繁体   中英

How to get selected list view item for context menu click event

I need help to get Selected list view item details, when context menu assigned to list view items is clicked.

 <ListView.Resources>
    <ContextMenu x:Key="GvRowMenu" ItemsSource="{Binding ContextMenuItems}">
        <ContextMenu.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image  Source="{Binding IconPath}"></Image>
                    <TextBlock  Text="{Binding Name}"></TextBlock>
                    <MenuItem 
                        Click="MenuItem_Click"
                        CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=DataContext.RunCommand}" />

This is a click event code

private void MenuItem_Click(object sender, RoutedEventArgs e)
    {
        //what needs to de here?
    }

I wrote this piece of code in my view model, but it doesnt trigger on execute method

RunCommand = new DelegateCommand<object>(OnRunCommand, CanRunCommand);

private void OnRunCommand(object obj)
    {
        // use the object here...
    }

    private bool CanRunCommand(object obj)
    {
        return true;
    }

Let me know, how can I handle this situation. Any examples related to same will be appreciated.

Thanks

you are mixing you methods... you can run an event or you can use a command, but not so much both together.

what you want is to bind the command:

<MenuItem Command="{Binding DataContext.RunCommand}" />

there are many wonderfull sources of info out there... here is one .

Thanks.., Well. below piece of code worked for me.

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
   MenuItem menuItem = (MenuItem)e.Source;
   ContextMenu contextMenu = menuItem.CommandParameter as ContextMenu;
   ListViewItem item = (ListViewItem)contextMenu.PlacementTarget;
   var x = ((myViewModel)(item.Content)).myModel;
   //'x' gives all required data of list view item
}

This is my XAML

<ListView.Resources>
   <ContextMenu x:Key="GvRowMenu" ItemsSource="{Binding ContextMenuItems}">
      <ContextMenu.ItemTemplate>
         <DataTemplate>
            <StackPanel Orientation="Horizontal">
               <Image  Source="{Binding ImagePath}"/>
               <TextBlock  Text="{Binding Name}"/>
               <MenuItem Click="MenuItem_Click" 
                         CommandParameter="{Binding 
                                 RelativeSource={RelativeSource 
                                 AncestorType={x:Type ContextMenu}}}"/>
            </StackPanel>
         </DataTemplate>
      </ContextMenu.ItemTemplate>
   </ContextMenu>
</ListView.Resources>

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