我正在尝试将列表框的Selected Index属性作为命令参数传递给上下文菜单项,我有命令绑定工作(感谢Will @ ElementName Binding from MenuItem in ContextMenu)但是我的命令参数有问题
<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>
答案 0 :(得分:1)
您可以将CommandParameter="{Binding }"
设置为将该行中的当前数据项传递给您的命令
修改强>
注意到你的命令在ContextMenu
。 ContextMenus不是WPF的默认Visual Tree的一部分,因此绑定的工作方式不同。要绑定到当前项,请使用以下命令:
<MenuItem Header="Remove"
Command="{Binding PlacementTarget.Tag.RemoveStoryClickCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding PlacementTarget.DataContext,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}}}" />
这将绑定DataContext
对ContextMenu
放置的任何控制,因此在这种情况下它将是Button.DataContext