WPF命令在ItemsControl中绑定ContextMenu项

时间:2017-11-09 13:08:56

标签: c# wpf contextmenu itemscontrol commandbinding

我的应用程序由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>

Command上的ContextMenu无法正常工作,因为它会尝试在ConnectionRemoveCommand对象上调用Connection而不是ConnectionViewModel DataContext的{​​{1}}。

如何UserControl绑定到CommandConnectionViewModelCommandParameter对象?

1 个答案:

答案 0 :(得分:1)

如果您将Tag的{​​{1}}属性绑定到Button的{​​{1}},则可以使用DataContext绑定ItemsControl PlacementTarget

ContextMenu