无法使用 CommunityToolkit.Mvvm 在视图模型中使用 ICommand 属性

Sam*_*Sam 14 c# mvvm community-toolkit-mvvm

在我的视图模型中,我想使用 CommunityToolkit.Mvvm 中的源生成器,但由于某种原因,我似乎无法[ICommand]在我的操作方法中使用属性。

我得到的错误是:

无法应用属性类“ICommand”,因为它是抽象的

这是我的视图模型模型的基类。

using CommunityToolkit.Mvvm.ComponentModel;

namespace MyApp.ViewModels
{
    public partial class BaseViewModel : ObservableObject
    {
        [ObservableProperty]
        bool isBusy = false;

        [ObservableProperty]
        string title = string.Empty;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的视图模型类:

public class MyViewModel : BaseViewModel
{
   [ObservableProperty]
   string firstName;

   [ObservableProperty]
   string lastName;

   [ICommand] // <-- This is where I get the error I mentioned above
   async Task DoSomething()
   {
       // Do something here...
   }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*viš 25

编辑

是的,他们已将其重命名ICommandAttributeRelayCommandAttribute. 8.0.0-preview4 发行说明的重大更改部分提到了这一点。

原答案

问题似乎是 @Luca Clavarino 在评论中提到的:

也许您不小心使用了 System.Windows.Input 中的 ICommand 接口,而不是ICommandAttributeCommunityTookit 中的接口。尝试替换[ICommand][CommunityToolkit.Mvvm.Input.ICommand],看看是否是这种情况。

我想我知道为什么这会发生在你身上。CommunityToolkit.Mvvm 8.0.0-preview4 中似乎ICommandAttribute缺少 ,因此 intellisense 不会提供该using CommunityToolkit.Mvvm.Input声明,而是提供using System.Windows.Input;

该问题可以通过降级到 CommunityToolkit.Mvvm 8.0.0-preview3来解决,该版本对我来说效果很好。

这是一个工作示例(使用 CommunityToolkit.Mvvm 8.0.0-preview3)。

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace MyApp.ViewModels
{
    public partial class BaseViewModel : ObservableObject
    {
        [ObservableProperty]
        bool isBusy = false;

        [ObservableProperty]
        string title = string.Empty;
    }

    public partial class MyViewModel : BaseViewModel
    {
        [ObservableProperty]
        string firstName;

        [ObservableProperty]
        string lastName;

        [ICommand] //works in 8.0.0-preview3
        async Task DoSomething()
        {
            // Do something here...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我还注意到,虽然8.0.0-preview4 中ICommandAttribute已经消失,RelayCommandAttribute有一个. 也许他们只是简单地重新命名了它。

在 8.0.0-preview4 中使用RelayCommandAttribute代替ICommandAttribute似乎有效。

[RelayCommand] //works in 8.0.0-preview4
async Task DoSomething()
{
    // Do something here...
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你!正如你所说,“[ICommand]”现在是“[RelayCommand]”,另一个重要的一点是,如果我们将方法命名为“DoSomething()”,生成的命令将是“DoSomethingCommand()”。这就是为什么我之前无法让 `[RelayCommand]` 工作的原因。一旦我引用了带有“Command”后缀的方法,它就工作得很好。再次感谢你的帮助! (3认同)

IKa*_*agh 17

接受的答案有很多文字只是说在8.0.0 Preview 4中该[ICommand]属性已重命名为[RelayCommand]. 它列在发行说明的重大更改中。