【问题标题】:Type reference cannot find type named Commands类型引用找不到名为 Commands 的类型
【发布时间】: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 绑定正确。固定问题。

标签: c# wpf xaml command


【解决方案1】:

Mathew 的帮助下,找到了解决办法:

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

所以在每个菜单项中,我添加了一个 CommandTarget 引用祖先 ContextMenu

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

这使得菜单项可点击。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多