views:

361

answers:

2

I have a ListBox that I have added a context menu to. I want one of the items in the context menu 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?

+1  A: 

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
A: 

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.

http://stackoverflow.com/questions/1013558/elementname-binding-from-menuitem-in-contextmenu

Joe