MAUI-CommunityToolkit-1 :👈 👉:MAUI-CommunityToolkit-3

πŸ“… Hour 2 – ObservableObject, ObservableProperty & Property Change Notifications

ο»Ώ

πŸ“… Hour 2 – ObservableObject, ObservableProperty & Property Change Notifications

πŸ“˜ 1. ObservableObject – The Core of MVVM Toolkit

ObservableObject is the base class that implements INotifyPropertyChanged for you.

Key Features:

  • πŸ“’ Automatically raises PropertyChanged
  • 🧱 Provides SetProperty() helper method
  • ✨ Works with source generators for reduced boilerplate

Basic Example:

public class CounterViewModel : ObservableObject
{
    private int count;

    public int Count
    {
        get => count;
        set => SetProperty(ref count, value);
    }
}

✨ 2. Using [ObservableProperty] Attribute

The [ObservableProperty] attribute auto-generates:

  • β—Ύ A public property
  • β—Ύ Backing field
  • β—Ύ PropertyChanged notifications

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);
}

🧲 3. Partial Methods – OnPropertyChanged Hooks

When you use [ObservableProperty], the toolkit generates methods for you:

  • πŸ”Ή OnPropertyChanging
  • πŸ”Ή OnPropertyChanged

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.


πŸ”— 4. [NotifyPropertyChangedFor] – Dependent Properties

Sometimes one property affects another. For example:

  • FullName depends on FirstName + LastName

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!


πŸ“₯ 5. Using ObservableProperty with Validation

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.


πŸ› οΈ 6. Hands-On Practice for Hour 2 (Important)

  • πŸ“ Create a ViewModel using [ObservableProperty]
  • πŸ”„ Add properties that depend on each other using [NotifyPropertyChangedFor]
  • πŸ§ͺ Add validation logic using OnXChanged or OnXChanging
  • πŸ”— Bind everything to your MAUI/WPF UI and test live updates
  • πŸ” Use breakpoints to observe auto-generated property change calls
  • πŸ“€ Display updated property values on UI when typing

πŸ“š 7. Example: Hour 2 Practice ViewModel

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:

  • Updated value prints in console
  • UI auto-updates
  • Details property refreshes automatically

🏁 Hour 2 Goals Achieved

  • 🎯 You understand ObservableObject deeply
  • ⚑ You can use [ObservableProperty] like a pro
  • πŸ”— You can create dependent UI properties
  • πŸ§ͺ You can add validation via partial methods

πŸ“ Hour 2 – MVVM Toolkit Quiz

πŸ“˜ Section A – Multiple Choice Questions

  1. Which attribute automatically generates a property with PropertyChanged support?
    a) [GeneratedProperty]
    b) [ObservableProperty]
    c) [AutoProperty]
    d) [Bindable]
  2. What method does ObservableObject use internally to update a field?
    a) UpdateValue()
    b) RaiseChanged()
    c) SetProperty()
    d) Notify()
  3. Which feature allows you to run custom logic before or after a property changes?
    a) PropertyChangedDelegate
    b) OnInitialize()
    c) Partial methods (OnXChanging / OnXChanged)
    d) PropertyInterceptor
  4. Which attribute updates a dependent property automatically?
    a) [DependsOn]
    b) [NotifyPropertyChangedFor]
    c) [LinkedProperty]
    d) [CascadeProperty]
  5. When using [ObservableProperty], what is generated by the toolkit?
    a) Only getters
    b) Only setters
    c) Full property + change notifications
    d) Nothing (you must write manually)

🧠 Section B – True or False

  1. True / False: ObservableObject already implements INotifyPropertyChanged.
  2. True / False: Partial methods like OnNameChanged are optional.
  3. True / False: [NotifyPropertyChangedFor] can only be used on methods, not properties.
  4. True / False: [ObservableProperty] generates a private field and a public property.
  5. True / False: If FirstName changes, dependent properties must be manually updated.

✍️ Section C – Short Answer Questions

  1. Explain what [ObservableProperty] does and give an example field using it.
  2. What problem does [NotifyPropertyChangedFor] solve? Give an example.
  3. Write a partial method that logs when a property called β€œScore” changes.
  4. Describe the purpose of SetProperty() inside ObservableObject.
  5. What are OnXChanging and OnXChanged methods? When would you use them?

πŸ’» Section D – Write the Output

Given this code:

public partial class PlayerViewModel : ObservableObject
{
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(Status))]
    private int level;

    public string Status => $"Level: {Level}";
}
  1. What happens in the UI when Level changes?
  2. Does Status update automatically?
  3. Which method is called behind the scenes?
Back to Index
MAUI-CommunityToolkit-1 :👈 👉:MAUI-CommunityToolkit-3
*