Here are multiple scenarios:
If you only ever replace the entire Person object and don't change its individual properties (you might select a different person from a list) all you need is to decorate the author
field with the ObservablePropertyAttribute
.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public partial class MyViewModel : ObservableObject
{
[ObservableProperty]
string title;
[ObservableProperty]
decimal price;
[ObservableProperty]
Person author;
}
This change will be reflected in the UI:
Author = anotherPerson;
and this one will NOT:
Author.FirstName = "James";
If you plan to change the persons individial properties, but keep the instance the same, you need to decorate the individual properties of the Person
object with the ObservablePropertyAttribute
.
public class Person : ObservableObject
{
[ObservableProperty]
string firstName;
[ObservableProperty]
string lastName;
}
public partial class MyViewModel : ObservableObject
{
[ObservableProperty]
string title;
[ObservableProperty]
decimal price;
public Person Author { get; } = new Person();
}
This change will be reflected in the UI:
Author.FirstName = "James";
and this one will NOT:
Author = anotherPerson;
Or do both and get the UI to reflect any changes, be it changing an individual property or the entire object instance.
public class Person : ObservableObject
{
[ObservableProperty]
string firstName;
[ObservableProperty]
string lastName;
}
public partial class MyViewModel : ObservableObject
{
[ObservableProperty]
string title;
[ObservableProperty]
decimal price;
[ObservableProperty]
Person author;
}
Any of these changes will be reflected in the UI:
Author = anotherPerson;
Author.FirstName = "James";