1

I have been trying out attributes and ran in an issue trying to use the RelayCommand attribute from the Community Toolkit.

I looked over the .NET Documentation on RelayCommand Attribute and tried to implement a simple example as follows:

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

namespace HelloWorld_WinUI3.ViewModels;

public partial class MainViewModel : ObservableObject
{
    public MainViewModel()
    {
    }

    private int _counter = 0;

    [RelayCommand]
    private async Task DoSomethingAsync()
    {
        await Task.Delay(1000);
        MyString = $"Hello {_counter++}";
    }

    [ObservableProperty]
    private string _myString = "Hello"; 
}

This produces the error: CS0616 'RelayCommand' is not an attribute class

Can someone explain what is wrong with this code and how to use the [RelayCommand] attribute properly?

JasonC
  • 139
  • 8

3 Answers3

2

The CommunityToolkit.Mvvm works with WinUI 3 and.NET7. Actually, I use it a lot, including every sample I create for StackOverflow answers.

I guess, you might be facing this known issue.

So, at this moment, try the v8.0 instead of v8.1.

Andrew KeepCoding
  • 7,040
  • 2
  • 14
  • 21
1

Using MVVM Source generators is still problematic for WinUI 3; I suggest using raw Relay command declaration:

public class MyViewModel : ObservableObject
{
    public MyViewModel()
    {
        IncrementCounterCommand = new RelayCommand(IncrementCounter);
    }

    private int counter;

    public int Counter
    {
        get => counter;
        private set => SetProperty(ref counter, value);
    }

    public ICommand IncrementCounterCommand { get; }

    private void IncrementCounter() => Counter++;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Samir
  • 11
  • 3
0

It appears the CommunityToolkit does not fully support WinUI3 or .NET 7 at this time Docs.

Running the same example on a WPF project works fine.

  • [ObservableProperty] seems to work in a WinUI3 project
  • [RelayCommand] does not work with WinUI3 project.
JasonC
  • 139
  • 8