2

I have a ListBox that I have added a ContextMenu to. I want one of the items in the ContextMenu to be bound to a command and I want the parameter passed to that command to be the currently selected item of the ListBox control. Here's my xaml:

<ListBox x:Name="selectedVascularBeds"             
         ItemsSource="{Binding Path=UserSelectedVascularBeds}"                    
         dd:DragDrop.IsDropTarget="True"
         dd:DragDrop.DropHandler="{Binding}"            
         DisplayMemberPath="VascularBedName">
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Remove" Command="{Binding Path=RemoveSelectedVascularBedCommand}"
                      CommandParameter="{Binding RelativeSource={RelativeSource 
                                         Mode=FindAncestor,
                                         AncestorType={x:Type ListBox}},
                                         Path=SelectedItem}"/>
        </ContextMenu>
    </ListBox.ContextMenu>
</ListBox>                      

This ListBox is part of a user control that is bound to a view model object. My command method on the underlying object gets called but the parameter passed in is always null.

I have tested changing the binding of the CommandParameter to simply {Binding} which results in the user control's data context being passed into my method - so I know that the command is working and passes parameters correctly. I just can't seem to get the correct binding to access the ListBox's SelectedItem property.

Help?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Joe
  • 447
  • 2
  • 8
  • 15

2 Answers2

3

the context menu is not a descendant of the list box. try an element name binding instead

<MenuItem Header="Remove" Command="{Binding Path=RemoveSelectedVascularBedCommand}" CommandParameter="{Binding ElementName=selectedVascularBeds, Path=SelectedItem}"/>
Aran Mulholland
  • 23,555
  • 29
  • 141
  • 228
1

The ElementName binding also didn't work, the parameter was still null and I found an error in the console output:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=selectedVascularBeds'. BindingExpression:Path=DataContext; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'CommandParameter' (type 'Object')

Searching for that error lead me to this link though and it looks like the Context menu is different and I can't achieve what I want the way I'm going about it.

ElementName Binding from MenuItem in ContextMenu

Community
  • 1
  • 1
Joe
  • 447
  • 2
  • 8
  • 15