| MAUI-ContentPage-ContentView :👈 | 👉:MAUI-CommunityToolkit-2 |
π Hour 1 β MVVM Basics & CommunityToolkit.Mvvm Introduction |
MVVM is a UI architectural pattern used in .NET MAUI, WPF, WinUI, Xamarin, UWP. It separates the UI from the logic.
Why MVVM?
The .NET Community Toolkit MVVM library is a lightweight, modern MVVM framework developed by Microsoft.
It provides:
Why use this toolkit?
INotifyPropertyChanged is an interface that notifies the UI whenever a property changes.
Manual Implementation Example:
public class Person : INotifyPropertyChanged
{
private string name;
public string Name
{
get => name;
set
{
if (name != value)
{
name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
π« This is long and repetitive β the Toolkit solves this!
ObservableObject already contains INotifyPropertyChanged logic.
Example:
public class PersonViewModel : ObservableObject
{
private string name;
public string Name
{
get => name;
set => SetProperty(ref name, value);
}
}
π No need to write events manually.
You can also use the [ObservableProperty] attribute to generate properties automatically.
Example:
public partial class PersonViewModel : ObservableObject
{
[ObservableProperty]
private string name;
}
This creates:
Generated property is equivalent to this:
// Auto-generated by the toolkit
public string Name
{
get => name;
set => SetProperty(ref name, value);
}
Use this command in your project folder:
dotnet add package CommunityToolkit.Mvvm
public partial class MainViewModel : ObservableObject
{
[ObservableProperty]
private string title = "Welcome to MVVM Toolkit";
[ObservableProperty]
private int counter;
public void Increment()
{
Counter++;
}
}
Bind this in XAML:
<Label Text="{Binding Title}" />
<Label Text="{Binding Counter}" />
Result:
| MAUI-ContentPage-ContentView :👈 | 👉:MAUI-CommunityToolkit-2 |