我有这个上下文菜单资源:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ContextMenu x:Key="FooContextMenu">
<ContextMenu.CommandBindings>
<CommandBinding Command="Help" Executed="{Binding ElementName=MainTabs, Path=HelpExecuted}" />
</ContextMenu.CommandBindings>
<MenuItem Command="Help">
<MenuItem.Icon>
<Image Source="../Resources/Icons/Help.png" Stretch="None" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</ResourceDictionary>
我想在两个地方重复使用它。首先,我想把它放在DataGrid
:
<DataGrid ContextMenu="{DynamicResource FooContextMenu}">...
ContextMenu
本身工作正常,但是我现在使用Executed="..."
打破了应用程序并抛出:
“System.InvalidCastException”类型的第一次机会异常 发生在PresentationFramework.dll
中附加信息:无法投射类型的对象 键入'System.Reflection.RuntimeEventInfo' 'System.Reflection.MethodInfo'。
如果我删除整个Executed="..."
定义,则代码可以正常工作(并且命令不执行任何操作/灰显)。一旦我右键单击网格/打开上下文菜单,就会抛出异常。
DataGrid
位于几个元素之下,但最终它们都低于TabControl
(称为MainTabs
),ItemsSource
设置为{FooViewModel
的集合1}} s,并且FooViewModel
我有一个方法HelpExecuted
我想要被调用。
让我们想象一下:
ItemsSource=ObservableCollection<FooViewModel>
,x:Name=MainTabs
)
为什么我会收到此错误?如何让上下文菜单命令“定位”FooViewModel
的{{1}}方法?
答案 0 :(得分:3)
这有帮助吗?
<ContextMenu>
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=HelpExecuted}" />
</Style>
</ContextMenu.ItemContainerStyle>
<MenuItem Header="Help" />
</ContextMenu>
答案 1 :(得分:3)
很遗憾,您无法绑定Executed
ContextMenu
因为它是一个事件。另一个问题是ContextMenu
在VisualTree
中不存在应用程序的其余部分。这两个问题都有解决方案。
首先,您可以使用Tag
的父控件的ContextMenu
属性来传递应用程序的DataContext
。然后,您可以DelegateCommand
使用CommandBinding
,然后就可以了。这是一个小样本,显示了您必须添加到项目中的View
,ViewModel
和DelegateCommand
实现。
<强> DelegateCommand.cs 强>
public class DelegateCommand : ICommand
{
private readonly Action<object> execute;
private readonly Predicate<object> canExecute;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{ }
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
this.execute = execute;
this.canExecute = canExecute;
}
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return canExecute == null ? true : canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
execute(parameter);
}
#endregion
}
<强> MainWindowView.xaml 强>
<Window x:Class="Application.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindowView" Height="300" Width="300"
x:Name="MainWindow">
<Window.Resources>
<ResourceDictionary>
<ContextMenu x:Key="FooContextMenu">
<MenuItem Header="Help" Command="{Binding PlacementTarget.Tag.HelpExecuted, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
</ContextMenu>
</ResourceDictionary>
</Window.Resources>
<Grid>
<TabControl ItemsSource="{Binding FooViewModels}" x:Name="MainTabs">
<TabControl.ContentTemplate>
<DataTemplate>
<DataGrid ContextMenu="{DynamicResource FooContextMenu}" Tag="{Binding}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Grid>
</Window>
<强> MainWindowView.xaml.cs 强>
public partial class MainWindowView : Window
{
public MainWindowView()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
<强> MainWindowViewModel.cs 强>
public class MainWindowViewModel
{
public ObservableCollection<FooViewModel> FooViewModels { get; set; }
public MainWindowViewModel()
{
FooViewModels = new ObservableCollection<FooViewModel>();
}
}
<强> FooViewModel.cs 强>
public class FooViewModel
{
public ICommand HelpExecuted { get; set; }
public FooViewModel()
{
HelpExecuted = new DelegateCommand(ShowHelp);
}
private void ShowHelp(object obj)
{
// Yay!
}
}
答案 2 :(得分:3)
我害怕MatthiasG打败了我。我的解决方案类似:
此处“帮助”命令由选项卡项的视图模型处理。将TestViewModel的引用传递给每个TestItemViewModel并在需要时将ShowHelp回调到TestViewModel中会很简单。
public class TestViewModel
{
public TestViewModel()
{
Items = new List<TestItemViewModel>{
new TestItemViewModel(), new TestItemViewModel() };
}
public ICommand HelpCommand { get; private set; }
public IList<TestItemViewModel> Items { get; private set; }
}
public class TestItemViewModel
{
public TestItemViewModel()
{
// Expression Blend ActionCommand
HelpCommand = new ActionCommand(ShowHelp);
Header = "header";
}
public ICommand HelpCommand { get; private set; }
public string Header { get; private set; }
private void ShowHelp()
{
Debug.WriteLine("Help item");
}
}
xaml
<Window.Resources>
<ContextMenu x:Key="FooMenu">
<MenuItem Header="Help" Command="{Binding HelpCommand}"/>
</ContextMenu>
<DataTemplate x:Key="ItemTemplate">
<!-- context menu on header -->
<TextBlock Text="{Binding Header}" ContextMenu="{StaticResource FooMenu}"/>
</DataTemplate>
<DataTemplate x:Key="ContentTemplate">
<Grid Background="#FFE5E5E5">
<!-- context menu on data grid -->
<DataGrid ContextMenu="{StaticResource FooMenu}"/>
</Grid>
</DataTemplate>
</Window.Resources>
<Window.DataContext>
<WpfApplication2:TestViewModel/>
</Window.DataContext>
<Grid>
<TabControl
ItemsSource="{Binding Items}"
ItemTemplate="{StaticResource ItemTemplate}"
ContentTemplate="{StaticResource ContentTemplate}" />
</Grid>
备用视图模型,以便将帮助命令定向到根视图模型
public class TestViewModel
{
public TestViewModel()
{
var command = new ActionCommand(ShowHelp);
Items = new List<TestItemViewModel>
{
new TestItemViewModel(command),
new TestItemViewModel(command)
};
}
public IList<TestItemViewModel> Items { get; private set; }
private void ShowHelp()
{
Debug.WriteLine("Help root");
}
}
public class TestItemViewModel
{
public TestItemViewModel(ICommand helpCommand)
{
HelpCommand = helpCommand;
Header = "header";
}
public ICommand HelpCommand { get; private set; }
public string Header { get; private set; }
}
ActionCommand
的一个非常简单的实现public class ActionCommand : ICommand
{
private readonly Action _action;
public ActionCommand(Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
_action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_action();
}
// not used
public event EventHandler CanExecuteChanged;
}
答案 3 :(得分:2)
您收到此错误,因为CommandBinding.Executed不是依赖项属性,因此您无法绑定它。
相反,使用后面的ResourceDictionary代码为CommandBinding.Executed事件指定事件处理程序,并在事件处理程序代码中调用FooViewModel.HelpExecuted()方法,如下所示:
<强> MainWindowResourceDictionary.xaml 强>
<ResourceDictionary x:Class="WpfApplication.MainWindowResourceDictionary"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication">
<DataTemplate DataType="{x:Type local:FooViewModel}">
<Grid>
<DataGrid ContextMenu="{DynamicResource FooContextMenu}"/>
</Grid>
</DataTemplate>
<ContextMenu x:Key="FooContextMenu">
<ContextMenu.CommandBindings>
<CommandBinding Command="Help" Executed="HelpExecuted"/>
</ContextMenu.CommandBindings>
<MenuItem Command="Help"/>
</ContextMenu>
</ResourceDictionary>
<强> MainWindowResourceDictionary.xaml.cs 强>
public partial class MainWindowResourceDictionary : ResourceDictionary
{
public MainWindowResourceDictionary()
{
InitializeComponent();
}
private void HelpExecuted(object sender, ExecutedRoutedEventArgs e)
{
var fooViewModel = (FooViewModel)((FrameworkElement)e.Source).DataContext;
fooViewModel.HelpExecuted();
}
}
答案 4 :(得分:1)
可以创建一个可以在XAML中配置为资源的适配器类,可以附加到Control以在那里创建CommandBindings,另一端可以绑定到ViewModel中应该是的方法当Button或MenuItem触发命令时调用。在这种情况下,命令将是RoutedCommand,无论您是选择其中一个预定义的WPF命令还是在应用程序中创建自定义RoutedCommand都无关紧要。
绑定到方法的技巧是
虽然这听起来很复杂,但好处是,一旦你将框架的各个部分组合在一起,你就可以只在XAML中重复使用它们,并且在ViewModel或后面的代码中根本就没有任何粘合代码。
你可以想象,这需要一些基础设施,代码比我想发布的更多。但是,我刚刚在我的博客上发表了一篇关于这个主题的文章http://wpfglue.wordpress.com/2012/05/07/commanding-binding-controls-to-methods/,通过博客,你可以下载完整的框架源代码和VB.Net中的一个例子。
应用于您的问题,XAML将如下所示:
在ContextMenu的定义中:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ContextMenu x:Key="FooContextMenu">
<!-- No CommandBindings needed here -->
<MenuItem Command="Help">
<MenuItem.Icon>
<Image Source="../Resources/Icons/Help.png" Stretch="None" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</ResourceDictionary>
在DataGrid的定义中
<DataGrid c:Commanding.CommandSet="{DynamicResource helpCommand}">
<DataGrid.Resources>
<f:ActionConverter x:Key="actionConverter"/>
<c:ActionCommand x:Key="helpCommand" Command="Help" ExecutedAction="{Binding Converter={StaticResource actionConverter}, ConverterParameter=HelpExecuted}"/>
<!-- DataGrid definition continued... -->