In .NET and Xamarin.Forms, which .NET MAUI is based on, We can use the [DependsOn] attribute from the Xamarin Community Toolkit's MVVM helpers to specify that one property depends on another. Here's an example of how you can use it:
using Xamarin.CommunityToolkit.MVVM;
public class MyViewModel : BaseViewModel
{
private string firstName;
private string lastName;
private string fullName;
public string FirstName
{
get => firstName;
set => SetProperty(ref firstName, value);
}
public string LastName
{
get => lastName;
set => SetProperty(ref lastName, value);
}
[DependsOn(nameof(FirstName), nameof(LastName))]
public string FullName
{
get => $"{FirstName} {LastName}";
}
}
I'm trying to achieve the same in .Net MAUI, but not getting this attribute over there. I'm using .Net 6 as of now for .Net MAUI.
For .NET MAUI the CommunityToolkit.Mvvm
is the one you want to migrate to (i.e. not Xamarin.CommunityToolkit.Mvvm
).
The changes you need to make are:
class
to partial class
ObservableObject
FirstName
and LastName
FirstName
and LastName
with ObservableProperty
attributeNotifyPropertyChangedFor
FullName
property is OK, but can be shortened furtherusing CommunityToolkit.Mvvm.ComponentModel;
public partial class MainViewModel : ObservableObject
{
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
string firstName;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
string lastName;
public string FullName =>
$"{FirstName} {LastName}";
}
Check out James Montemagno's YouTube videos on the topic, such as Even More MVVM Source Generator Awesomeness for .NET Developers
[EDIT]
A .NET 6 working sample of the above can be found here: https://github.com/stephenquan/maui-dotnet-6-app
Check https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/ the documentation where it mentions that it targets both .NET Standard and special mention for the .NET 6 target:
This package targets .NET Standard so it can be used on any app platform: UWP, WinForms, WPF, Xamarin, Uno, and more; and on any runtime: .NET Native, .NET Core, .NET Framework, or Mono. It runs on all of them. The API surface is identical in all cases, making it perfect for building shared libraries.
Additionally, the MVVM Toolkit also has a .NET 6 target, which is used to enable more internal optimizations when running on .NET 6. The public API surface is identical in both cases, so NuGet will always resolve the best possible version of the package without consumers having to worry about which APIs will be available on their platform.