【问题标题】:.net core 3.1 inserting CommandManager-class into class library-project.net core 3.1 将 CommandManager 类插入类库项目
【发布时间】:2020-03-01 22:09:45
【问题描述】:

我目前正在尝试将几年前创建的 MVVM 库从 .NET 4.5 迁移到 .NET Core 3.1。 这出乎意料地好,但目前我正在为我在 RelayCommand-Class 中使用的 CommandManager-Class 苦苦挣扎。

我正在为我的 RelayCommand-Class 的 CanExecute 事件处理程序使用 CommandManager:

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
}

在我研究这个问题的过程中,我发现 System.Windows.Input 不是 .NET Core 的一部分。有许多解决方案建议将 Projecttarget 从 Classlibrary 切换到 WPF-Application 或嵌入 PresentationCore-Assembly。

这些解决方案对我不起作用——我猜主要是因为我使用了普通的 .NET Core 类库项目。

所以我想问一下它们是否存在于 .NET Core 中的类似类? 或者如果我尝试编写自己的 CommandManager-Class 来替换它会更好吗?

目前最后一个选项是从我的库中提取 Commanding-part 并将其直接放入使用该库的项目中(一个 avalonia 客户端应用程序)。 但这感觉不对……

亲切的问候

地理编码器

【问题讨论】:

    标签: c# .net .net-core class-library


    【解决方案1】:

    将您的 .csproj 文件更改为:

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

    【讨论】:

    • 您好 RBasniak,感谢您的回复。 :) 我试图将我的项目的 Sdk 更改为 WindowsDesktop:&lt;Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"&gt; &lt;PropertyGroup&gt; &lt;TargetFramework&gt;netcoreapp3.1&lt;/TargetFramework&gt; &lt;/PropertyGroup&gt; 但这不起作用。我计划在应该在 Windows 和 Linux 上运行的 .net 核心应用程序中使用该库,所以如果我想要多平台支持,我不确定更改 SDK 是否是个好主意?
    • 您是否加入了&lt;UseWPF&gt;true&lt;/UseWPF&gt;?但我认为 System.Windows 命名空间下的类不应该在多平台库上使用,这就是为什么它们不在 .NET Core 中,它们只在 Windows 上工作。
    • 啊! &lt;UseWPF&gt;true&lt;UseWPF&gt; - 这就是我所监督的。现在它起作用了。好的,感谢您的解释 - 所以我的想法是正确的,在 .NET Core-Applications 中使用特定于 Windows 的类不是一个好主意。所以我想现在唯一的解决方案是编写一个自己的命令管理器类,专门基于 .netCore-Components 对吧?
    • 如果这解决了问题中的问题,您介意接受我的回答吗? :) 谢谢!
    猜你喜欢
    • 2022-08-15
    • 1970-01-01
    • 2022-11-01
    • 2020-05-02
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 2016-11-18
    相关资源
    最近更新 更多