簡體   English   中英

WPF命令綁定ItemsControl中的ContextMenu項

[英]WPF Command Binding of ContextMenu Item inside ItemsControl

我的應用程序由一個帶有ContentControlMainWindow組成,我根據所選菜單更改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>

CommandContextMenu不起作用,因為它試圖調用ConnectionRemoveCommandConnection的對象,而不是ConnectionViewModel這是DataContext的的UserControl

如何將綁定CommandConnectionViewModelCommandParameter作為Connection對象?

如果將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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM