类型引用找不到名为Commands的类型

本文关键字:类型 Commands 引用 找不到 | 更新日期: 2023-09-27 18:28:06

我希望在我的应用程序中有自定义的Command响应。所以我按照这个答案的说明,为我的命令创建了一个静态类:

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'

更新

马修消除了这些错误,但是,包含这些命令的菜单项仍然是灰色的。相关代码:

<TreeView ...>
    <ContextMenu>
        <MenuItem Command="{x:Static local:Commands.Create}"/>
    </ContextMenu>
    ...
</TreeView>

MyControl.xaml.cs

//...
private void CanCreateThing(object sender, CanExecuteRoutedEventArgs e) {
    e.CanExecute = true;
}
//...

类型引用找不到名为Commands的类型

在Mathew的帮助下,找到了一个修复程序:

首先,我必须用{x:Static local:Commands.Create}替换local:Commands.Create的所有实例。但是,菜单项仍然是灰色的。

因此,在每个菜单项中,我添加了一个引用祖先ContextMenu:的CommandTarget

<MenuItem Command="{x:Static local:Commands.CreateTrigger}"
                    CommandTarget="{Binding PlacementTarget, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"/>

这使得菜单项可以点击。