I'm using CommunityToolkit.Mvvm in my WPF project.
As usual, I'm declaring only my private backing fields and I'm adding the [ObservableProperty]
attribute on them. I'd like some generated properties to be "required", so that when an instance of the class is created, it is mandatory to set these properties. Is there a way to achieve this behaviour from source code generators in CommunityToolkit.Mvvm?
At the time of writing, it isn't released yet1 but support for [ObservableProperty] on partial properties is on the way. This means, instead of declaring the backing field2 you will be able to use the generator with a required partial property as follows:
public partial class Foo : ObservableObject
{
[ObservableProperty]
public required partial string Bar { get; set; }
}
Note that partial properties come with C# 13.
1 You can use preview versions by using nuget package sources like https://pkgs.dev.azure.com/dotnet/CommunityToolkit/_packaging/CommunityToolkit-PullRequests/nuget/v3/index.json
2 This new version comes with a code analysis rule (MVVMTK0042) that suggests using [ObservableProperty]
on partial properties instead of fields and a code fix provider for it so you can do the switch automatically