ItemsControl 中 ContextMenu 项的 WPF 命令绑定

WPF Command Binding of ContextMenu Item inside ItemsControl

我的应用程序由 MainWindowContentControl 组成,我根据所选菜单更改 ViewModel。

我显示为内容的其中一个 UserControl 包含以下 WrapPanel

<UserControl ...>
    <Grid>
        <WrapPanel>
            <ItemsControl ItemsSource="{Binding Connections}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Button Command="{Binding DataContext.ConnectionSelectCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
                                CommandParameter="{Binding}"
                                FocusManager.FocusedElement="{Binding ElementName=InstanceName}"
                                Style="{DynamicResource DashboardButton}">
                            <TextBlock TextWrapping="Wrap" HorizontalAlignment="Center" Text="{Binding Name}" />
                            <Button.ContextMenu>
                                <ContextMenu>
                                    <MenuItem Header="Delete"
                                              Command="{Binding ConnectionRemoveCommand}"
                                              CommandParameter="{Binding}" />
                                </ContextMenu>
                            </Button.ContextMenu>
                        </Button>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel Orientation="Horizontal" />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </WrapPanel>
    </Grid>
</UserControl>

ContextMenu 上的 Command 不起作用,因为它试图在 Connection 对象上调用 ConnectionRemoveCommand 而不是 ConnectionViewModel UserControlDataContext

如何Command 绑定到 ConnectionViewModelCommandParameterConnection 对象?

如果将 ButtonTag 属性 绑定到 ItemsControlDataContext,则可以使用 PlacementTargetContextMenu:

<Button Command="{Binding DataContext.ConnectionSelectCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
        CommandParameter="{Binding}"
        FocusManager.FocusedElement="{Binding ElementName=InstanceName}"
        Style="{DynamicResource DashboardButton}"
        Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ItemsControl}}">
    <TextBlock TextWrapping="Wrap" HorizontalAlignment="Center" Text="{Binding Name}" />
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete"
                    Command="{Binding PlacementTarget.Tag.ConnectionRemoveCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                    CommandParameter="{Binding}" />
        </ContextMenu>
    </Button.ContextMenu>
</Button>