CommunityToolkit / dotnet

.NET Community Toolkit is a collection of helpers and APIs that work for all .NET developers and are agnostic of any specific UI platform. The toolkit is maintained and published by Microsoft, and part of the .NET Foundation.
https://docs.microsoft.com/dotnet/communitytoolkit/?WT.mc_id=dotnet-0000-bramin
Other
3.07k stars 299 forks source link

Generate source for RelayCommandAttribute on record as well #647

Open virzak opened 1 year ago

virzak commented 1 year ago

Overview

Records should also be able to generate RelayCommand just like classes do.

API breakdown

No new API

Usage example

Data layer has a record:

public record DataRecord(int Stuff, IList<int>ListOfStuff);

In the MVVM layer we want to provide commands to add or remove from the ListOfStuff:

public partial record DataRecordVM(DataRecord dr) : DataRecord(dr.Stuff, dr.ListOfStuff)
{
}

Inside DataRecordVM I'd like to add to the list

[RelayCommand]
private void Add(int newStuff) => ListOfStuff.Add(newStuff);

Breaking change?

No

Alternatives

The alternative is to instantiate RelayCommand by hand.

The other alternative is to use a class which has the record as its member, but it is too verbose:

public partial class DataClassVM(DataRecord dr)
{
    [RelayCommand]
    private void Add(int newStuff) => dr.ListOfStuff.Add(newStuff);

    // expose if necessary
    public IList<int> DataRecord => dr.ListOfStuff;
    public int Stuff => dr.Stuff;
}

Additional context

No response

Help us help you

Yes, I'd like to be assigned to work on this item