我有一个包含RoutedUICommand的静态类,我想在绑定中使用它。
public static class CommandLibrary
{
public static ProjectViewModel Project { get; set; }
public static RoutedUICommand AddPage { get; private set; }
static CommandLibrary()
{
AddPage = new RoutedUICommand("AddPage", "AddPage", typeof(CommandLibrary));
}
public static void AddPage_Executed(object sender, ExecutedRoutedEventArgs args)
{
Project.AddPage();
}
public static void AddPage_CanExecute(object sender, CanExecuteRoutedEventArgs args)
{
// We need a project before we can add pages.
if (Project != null)
{
args.CanExecute = true;
}
else
{
// Did not find project, turning Add Page off.
args.CanExecute = false;
}
}
}
当我尝试为此AddPage命令创建CommandBinding时,VS会抱怨说它找不到Window1中的AddPage_CanExecute...这毫无意义,因为我放置的代码应该使得这个XAML没问题:
<Window x:Class="MyProject.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyProject">
<Menu>
<Menu.CommandBindings>
<CommandBinding Command="local:CommandLibrary.AddPage"
Executed="AddPage_Executed" CanExecute="AddPage_CanExecute" />
</Menu.CommandBindings>
<MenuItem Header="_Page">
<MenuItem Header="_New" Command="local:CommandLibrary.AddPage" />
</MenuItem>
</Menu>
</Window>
我也尝试了不包含Menu.CommandBindings部分,只是简单地使用这段代码(根据这个问题的建议,但没有具体说明):
<MenuItem Header="_New" Command="{x:Static local:CommandLibrary.AddPage}" />
这样做可以停止错误的流,但是生成的菜单项总是被禁用!CanExecute似乎从未被调用。我认为在这种情况下绑定失败了,尽管更加安静。
为什么VS会讨厌我的命令并拒绝查找Executed和CanExecute方法的正确位置?我看到过很多例子(例如Matthew McDonald的Pro WPF和几个自定义命令教程),都像我一样这样做。