0
votes

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>
1

1 Answers

2
votes

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