| MAUI-CommunityToolkit-1 :👈 | 👉:MAUI-CommunityToolkit-3 |
π Hour 2 β ObservableObject, ObservableProperty & Property Change Notifications |
ObservableObject is the base class that implements INotifyPropertyChanged for you.
Key Features:
Basic Example:
public class CounterViewModel : ObservableObject
{
private int count;
public int Count
{
get => count;
set => SetProperty(ref count, value);
}
}
The [ObservableProperty] attribute auto-generates:
Example:
public partial class UserViewModel : ObservableObject
{
[ObservableProperty]
private string username;
[ObservableProperty]
private int age;
}
This generates (automatically):
public string Username
{
get => username;
set => SetProperty(ref username, value);
}
When you use [ObservableProperty], the toolkit generates methods for you:
You can write your own logic by adding partial methods.
Example:
public partial class ProfileViewModel
{
[ObservableProperty]
private string email;
partial void OnEmailChanged(string value)
{
Console.WriteLine("Email changed to: " + value);
}
}
π‘ Useful for validation, logging, event dispatching.
Sometimes one property affects another. For example:
Example:
public partial class PersonViewModel : ObservableObject
{
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
private string firstName;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
private string lastName;
public string FullName => $"{FirstName} {LastName}";
}
π Now whenever FirstName or LastName changes β FullName updates automatically!
Example with simple validation:
public partial class LoginViewModel : ObservableObject
{
[ObservableProperty]
private string username;
partial void OnUsernameChanging(string value)
{
if (string.IsNullOrWhiteSpace(value))
Console.WriteLine("Username cannot be empty");
}
}
π‘ You can build real-time validations easily here.
This covers auto-properties, dependent properties, partial methods.
public partial class StudentViewModel : ObservableObject
{
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(Details))]
private string name;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(Details))]
private int marks;
public string Details => $"{Name} scored {Marks} marks";
partial void OnNameChanged(string value)
{
Console.WriteLine("Name updated to: " + value);
}
}
When Name or Marks changes:
Given this code:
public partial class PlayerViewModel : ObservableObject
{
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(Status))]
private int level;
public string Status => $"Level: {Level}";
}
| MAUI-CommunityToolkit-1 :👈 | 👉:MAUI-CommunityToolkit-3 |