0

I am trying to pass a listbox's Selected Index property as a command paramater to a context menu item, I have the command binding working (thanks to Will @ ElementName Binding from MenuItem in ContextMenu) but I'm have trouble with my command paramater.

<UserControl>
    <ListBox ItemsSource="{Binding myItems}">
        <ListBox.Resources> <!-- The selected item is the item the mouse is over  -->
            <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver,RelativeSource={RelativeSource Self}}" 
                     Value="True">
                        <Setter Property="IsSelected" Value="True" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ListBox.Resources>

        <ListBox.ItemTemplate>
            <DataTemplate>
                <Button Content="Edit" Grid.Column="4" Grid.Row="0" Tag="{Binding DataContext, ElementName=ProductBacklog}">
                    <Button.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="Remove" 
                                Command="{Binding PlacementTarget.Tag.RemoveStoryClickCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" 
                                CommandParameter="{Binding <!--I NEED TO BIND TO THE LISTBOX-->, Path=SelectedIndex}"/>
                        </ContextMenu>
                    </Button.ContextMenu>
                </Button>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>
</UserControl>
Community
  • 1
  • 1
Eamonn McEvoy
  • 8,876
  • 14
  • 53
  • 83

1 Answers1

2

You can set the CommandParameter="{Binding }" to pass the current data item in that row to your Command

Edit

Just noticed your command is in a ContextMenu. ContextMenus are not part of WPF's default Visual Tree, so bindings do not work the same way. To bind to the current item, use the following:

<MenuItem Header="Remove" 
          Command="{Binding PlacementTarget.Tag.RemoveStoryClickCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" 
          CommandParameter="{Binding PlacementTarget.DataContext, 
              RelativeSource={RelativeSource FindAncestor, 
              AncestorType={x:Type ContextMenu}}}" />

This will bind to the DataContext of whatever control the ContextMenu is placed on, so in this case it will be Button.DataContext

Rachel
  • 130,264
  • 66
  • 304
  • 490
  • 1
    thanks for the help, I made an error in my original question though, it is the item index I need, not the actual item. Is this possible? – Eamonn McEvoy Nov 25 '11 at 15:46
  • 1
    @EamonnMcEvoy Hrrrm perhaps set your Button's DataContext to a RelativeSource binding pointing to the ListBox's SelectedIndex? `` – Rachel Nov 25 '11 at 15:56