Class library does not recognize CommandManager class
Asked Answered
S

1

25

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.

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 "CommandManager does not exists in the current context". In my usings I have the following (which should be enough)

 using System;
 using System.Windows.Input;

Any ideas why I can't do this in a "class library project" ?

Swaziland answered 5/6, 2013 at 22:14 Comment(0)
F
56

Go to the "References" part of your class library and select "Add Reference". Look for an assembly called "PresentationCore" and add it.

Then in your class file add the using statement using System.Windows.Input;

You will then be able to access the CommandManager as you expect.

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.

Frontispiece answered 5/6, 2013 at 23:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.