2

I have a ContextMenu (from the Silverlight Toolkit) inside a DataTemplate used as the ItemTemplate of a ListBox:

<DataTemplate x:Key="BillItemDataTemplate">
  <Grid Margin="0,0,0,12" x:Name="ItemGrid">
    <kit:ContextMenuService.ContextMenu>
      <kit:ContextMenu>
        <kit:MenuItem Header="delete item" 
                      Command="{Binding ???????.DeleteItemCommand}"
                      CommandParameter="{Binding}" />
      </kit:ContextMenu>
    </kit:ContextMenuService.ContextMenu>
    [...]
  </Grid>
</DataTemplate>

How can I tell the ContextMenu.Command to bind to a property on the view-model exposed by the outer DataContext (i.e. the one that applies to the ListBox)? If I'm right, I cannot use WPF relative declarations as explained here.

I would prefer if my child view-models wouldn't require a reference to the "parent" view-model.

Community
  • 1
  • 1
Martin Plante
  • 4,553
  • 3
  • 33
  • 45

2 Answers2

1

Use can use ElementName bindings. I don't have the code here but you can do something like

DataContext="{Binding ElementName=LayoutRoot,Path=DataContext}"

Where LayoutRoot is an element outside the ListBox, or the ListBox itself.

Nigel Sampson
  • 10,549
  • 1
  • 28
  • 31
  • I don't want to change the DataContext of the MenuItem since I'm using it for CommandParameter. I tried Command="{Binding DataContext.DeleteItemCommand, ElementName=LayoutRoot}" but still doesn't work. Is there a diff between SL3 and WP7? – Martin Plante Apr 29 '11 at 03:30
  • I'm not sure why it's not working to be honest I've used the above issue to solve this exact problem with Context Menus. What I'd do is start simple, trying the ListBox element name, trying without the data context to see which part isn't working correctly. – Nigel Sampson Apr 30 '11 at 20:56
1

For the record, I've taken the habit of having an ICommand property on every child view-model, set to the parent ICommand when each is created, again with CommandParameter="{Binding}".

Martin Plante
  • 4,553
  • 3
  • 33
  • 45