WPF:将ListBox ContextMenu的command参数绑定到ListBox的Selected Item

Adr*_*n S 3 c# data-binding wpf listbox

是否可以将ListBox ContextMenu的CommandParameter绑定到ListBox 的 Selected Item?我应该说 ContCommand 位于主窗口中,并在单击上下文菜单项时调用它 - 但是,我需要让参数正常工作。

我试过了,但绑定失败:

<Window x:Class="ListBoxContextMenu.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ListBoxContextMenu"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">

    <Grid>
        <StackPanel>
            <TextBlock Text="ListBox here:"/>
            <ListBox ItemsSource="{Binding Items}" MinHeight="100" TabIndex="0" x:Name="LB">
                <ListBox.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Foo" Command="{Binding ContCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}},Path=SelectedItem}"/>
                    </ContextMenu>
                </ListBox.ContextMenu>
            </ListBox>
        </StackPanel>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

主窗口的 C# 代码:

using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using MvvmFoundation.Wpf;

    namespace ListBoxContextMenu
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                DataContext = this;
                Loaded += (sender, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                ContCommand = new RelayCommand<object>((object o) =>
                {
                    System.Diagnostics.Debug.WriteLine("Context Menu pressed");
                });
            }

            public ObservableCollection<string> Items { get; set; } = new ObservableCollection<string>{"Fred", "Jim", "Sheila"};
            public RelayCommand<object> ContCommand { get; set; }
        }
    }
Run Code Online (Sandbox Code Playgroud)

mm8*_*mm8 11

ListBox不是的视觉祖先ContextMenu,因为后者驻留在自己的视觉树。

但是您可以绑定到PlacementTargetContextMenu,即ListBox

这有效:

<ListBox ItemsSource="{Binding Items}" MinHeight="100" TabIndex="0" x:Name="LB">
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Foo" Command="{Binding ContCommand}" 
                              CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}},
                                Path=PlacementTarget.SelectedItem}"/>
        </ContextMenu>
    </ListBox.ContextMenu>
</ListBox>
Run Code Online (Sandbox Code Playgroud)