Search code examples
c#.net.net-coreclass-library

.net core 3.1 inserting CommandManager-class into class library-project


I'm currently on trying out to migrate an MVVM-library I've created a few years ago from .NET 4.5 to .NET Core 3.1. That went surprisingly good, but at the moment I'm struggling with the CommandManager-Class that I use in my RelayCommand-Class.

I'm using the CommandManager for the CanExecute Eventhandler of my RelayCommand-Class:

public class RelayCommand : ICommand
{
    #region Properties
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;
    #endregion

    #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

    #region ICommand Members

    [DebuggerStepThrough]
    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
}

During my research on that problem I've found out, that the System.Windows.Input is not part of.NET Core. There are many Solutions that recommend to switch the Projecttarget from Classlibrary to WPF-Application or embedding the PresentationCore-Assembly.

These Solutions didn't work for me - mostly I guess because of my usage of a normal .NET Core Classlibrary Project.

So i wanted to ask if their is a similar class existing inside of .NET Core? Or would it be better if I try to code my own CommandManager-Class to replace it?

Currently the last option would be to extract the Commanding-part out of my library and put it directly into the project that uses the library (an avalonia client application). But that doesn't feel right...

Kind regards

GeoCoder


Solution

  • Change your .csproj file to this:

    <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
    
      <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <UseWPF>true</UseWPF>
      </PropertyGroup>
    
    </Project>