ItemsControl 中上下文菜单项的 WPF 命令绑定



我的应用程序由一个带有ContentControlMainWindow组成,我根据所选菜单更改视图模型。

我显示为内容的用户控件之一包含以下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,则可以使用ContextMenuPlacementTarget绑定到它:

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

最新更新