wpf 类库无法识别 CommandManager 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16950813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Class library does not recognize CommandManager class
提问by koala
I'm developing WPF applications and I want to reuse my classes that are the same in all those applications so I can add them as a reference.
我正在开发 WPF 应用程序,我想重用我在所有这些应用程序中相同的类,以便我可以将它们添加为参考。
In my case I have a class for my Commands:
就我而言,我的命令有一个类:
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
}
This works perfect in my application, but when I want to make a class library which I just want to add as a reference in my project, visual studio can't build because "CommandManagerdoes not exists in the current context". In my usings I have the following (which should be enough)
这在我的应用程序中非常有效,但是当我想创建一个我只想在我的项目中添加为参考的类库时,visual studio 无法构建,因为“当前上下文中不存在CommandManager”。在我的使用中,我有以下内容(应该足够了)
using System;
using System.Windows.Input;
Any ideas why I can't do this in a "class library project" ?
有什么想法为什么我不能在“类库项目”中做到这一点?
回答by Gayot Fow
Go to the "References" part of your class library and select "Add Reference". Look for an assembly called "PresentationCore" and add it.
转到类库的“参考”部分,然后选择“添加参考”。查找名为“PresentationCore”的程序集并添加它。
Then in your class file add the using statement using System.Windows.Input;
然后在您的类文件中添加 using 语句 using System.Windows.Input;
You will then be able to access the CommandManager as you expect.
然后,您将能够按预期访问 CommandManager。
Just adding: lots of guys when they go to create a class library, they select "WPF Custom Control Library" and then erase the "Class1.cs" file. It's a shortcut that automatically adds the right namespaces to your library. Whether it's a good or bad shortcut is anybody's call, but I use it all the time.
只是补充一点:很多人在创建类库时,选择“WPF 自定义控件库”,然后删除“Class1.cs”文件。这是一个快捷方式,可以自动将正确的命名空间添加到您的库中。捷径是好是坏是任何人的要求,但我一直在使用它。

