类库无法识别CommandManager类。

25

我正在开发WPF应用程序,希望能够重复使用那些在这些应用程序中相同的类,以便将它们作为引用添加。

就我的情况而言,我有一个用于命令的类:

public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {

    }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }
    #endregion // Constructors

    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    #endregion // ICommand Members
}

这在我的应用程序中完美运行,但当我想要制作一个类库,只想将其作为引用添加到我的项目中时,Visual Studio无法构建,因为“CommandManager在当前上下文中不存在”。在我的 usings 中,我有以下内容(应该足够)

 using System;
 using System.Windows.Input;

有什么想法,为什么我不能在“类库项目”中这样做?

1个回答

56

转到类库的“引用”部分,选择“添加引用”。查找名为“PresentationCore”的程序集并添加它。

然后,在您的类文件中添加using语句using System.Windows.Input;

您将能够像预期一样访问CommandManager。

仅需添加:许多人在创建类库时选择“WPF自定义控件库”,然后删除“Class1.cs”文件。这是一个快捷方式,可以自动添加正确的命名空间到您的类库中。是否是好还是坏的快捷方式由任何人决定,但我经常使用它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接