【发布时间】:2025-11-30 07:20:03
【问题描述】:
假设我有一个带有 ContextMenu 的 ListView。我想将它用作一个名为ListViewWithContextMenu 的单独控件。如何从 ContextMenu 重定向命令绑定,以便它们在 ListViewWithContextMenu 中可见?
示例代码:
ListViewWithContextMenu.xaml
<ListView x:Class="WpfApplication4.ListViewWithContextMenu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication4"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ListViewWithContextMenu}}, Path= PreviewCommand}" />
</ContextMenu>
</ListView.ContextMenu>
ListViewWithContextMenu.xaml.cs
using System.Windows;
using System.Windows.Input;
namespace WpfApplication4
{
public partial class ListViewWithContextMenu
{
public ICommand PreviewCommand
{
get { return (ICommand)GetValue(PreviewCommandProperty); }
set { SetValue(PreviewCommandProperty, value); }
}
public static readonly DependencyProperty PreviewCommandProperty =
DependencyProperty.Register("PreviewCommand", typeof(ICommand), typeof(ListViewWithContextMenu));
public ListViewWithContextMenu()
{
InitializeComponent();
}
}
}
MainWindow.xaml
<Window x:Class="WpfApplication4.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:WpfApplication4"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext><local:MainWidnowViewModel></local:MainWidnowViewModel></Window.DataContext>
<Grid>
<local:ListViewWithContextMenu PreviewCommand="{Binding Preview}"></local:ListViewWithContextMenu>
</Grid>
</Window>
MainWindowViewModel.cs
using System.Windows;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
namespace WpfApplication4
{
public class MainWidnowViewModel
{
public MainWidnowViewModel()
{
Preview = new DelegateCommand(PreviewMethod);
}
private void PreviewMethod()
{
MessageBox.Show("PREVIEW");
}
public ICommand Preview { get; set; }
}
}
此代码不会调用我想要实现的 ViewModel 中的 PreviewMethod
【问题讨论】:
-
我有办法解决你的问题。给我一点时间把它写下来作为答案......