【发布时间】:2010-11-19 20:26:56
【问题描述】:
我有一个静态类,其中包含我想在绑定中使用的 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 部分,而是简单地使用它(根据 this question 建议但不具体):
<MenuItem Header="_New" Command="{x:Static local:CommandLibrary.AddPage}" />
这阻止了错误流,但它生成的菜单项总是被禁用! CanExecute 似乎永远不会被调用。我假设在这种情况下绑定也失败了,尽管更安静。
为什么 VS 讨厌我的命令并拒绝在正确的位置查找 Executed 和 CanExecute 方法?我已经看到了很多示例(在 Pro WPF 中 由 Matthew McDonald 和几个在线自定义命令教程提供),我正在这样做。
【问题讨论】:
标签: c# wpf data-binding xaml command