【发布时间】:2016-03-31 15:00:23
【问题描述】:
我想在我的应用程序中自定义Commands 来响应。
所以我按照this answer 上的说明为我的命令创建了一个静态类:
namespace MyNamespace {
public static class Commands {
public static readonly RoutedUICommand Create = new RoutedUICommand(
"Create Thing", nameof(Create),
typeof(MyControl)
);
}
}
然后我尝试在我的 UserControl 上使用它:
<UserControl x:Class="MyNamespace.MyControl"
...boilerplate...
xmlns:local="clr-namespace:MyNamespace">
<UserControl.CommandBindings>
<CommandBinding Command="local:Commands.Create"
CanExecute="CanCreateThing"
Executed="CreateThing"/>
</UserControl.CommandBindings>
...the control's contents...
</UserControl>
方法CanCreateThing 总是将CanExecute 设置为true。 CreateThing 目前什么都不做。
我在窗口 XAML 中使用 MyControl 时收到此错误:
Type reference cannot find type named '{clr-namespace:MyNamespace;assembly=MyAssembly}Commands'.
还有这个在Command="..."属性中的绑定。
Invalid value for property 'Command': 'Microsoft.VisualStudio.DesignTools.Xaml.LanguageService.Semantics.XmlValue'
更新
Mathew 消除了错误,但是带有这些命令的菜单项仍然是灰色的。相关代码:
<TreeView ...>
<ContextMenu>
<MenuItem Command="{x:Static local:Commands.Create}"/>
</ContextMenu>
...
</TreeView>
MyControl.xaml.cs
//...
private void CanCreateThing(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
}
//...
【问题讨论】:
-
在绑定中尝试
Command="{x:static local:Commands.Create}"。 -
@Mathew 请参阅编辑。
-
再次检查 DeleteItem 命令的 CanExecute 实际上指向 CanCreateThing 方法。
-
@E-Bat Woops
DeleteItem是另一个命令,我的意思是写Create。如上所示,它的CanExecute绑定正确。固定问题。