Hermios
Hermios

Reputation: 634

ContextMenu in ListView, click on a menuitem doesn't fire the expected command

I have a listview, with contextmenu associated to each listviewitem. But a click on a menuitem doesn't call the corresponding Command myCommand. myCommand is linked to a "Execute" and a "Can Execute" methods. The "Can Execute" method works, but not the "Execute" one. it has a parameter. If I remove the datacontext, the "Execute" Method is called, but the parameter is always null. My code in xaml:

<ListView.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Open Directory " 
                              DataContext="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                              Command="{Binding OpenLink}"
                              CommandParameter="{Binding Path=LocalPath}"/>
                </ContextMenu>
            </ListView.ContextMenu>

Short explanation : Each Item from my list has a property LocalPath. When I right click on an item, and select "Open Directory", it is supposed to open the directory for this item. Thanks for your help

Niko

Upvotes: 0

Views: 834

Answers (1)

dkozl
dkozl

Reputation: 33364

Setting DataContext changes default binding context for all bindings. If you want to get LocalPath from ListView.SelectedItem you can use RelativeSource binding against that binding only but you need to use PlacementTarget to get from ContextMenu to ListView.

<MenuItem 
    Header="Open Directory"
    CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem.LocalPath}"
    Command="{Binding OpenLink}"/>

Upvotes: 4

Related Questions