C#C
C#5mo ago
HFrederick

✅ How to bind an object observable property with mvvm community toolkit in wpf

I'm trying to migrate a wpf app to use the mvvm toolkit. I have a viewmodel and model setup that looks like this:
public partial class MyViewmodel : ObservableObject
{
    [ObservableProperty]
    private Book? book;
    
    [RelayCommand]
    public void LoadBook()
    {
        Book = FileLoaderService.Load("filepathhere.zip");
    }
    
    [RelayCommand]
    public void AddChapter()
    {
        Book.Chapters.Add(new Chapter("New chapter", "new content"));
    }
    [RelayCommand]
    public void ChangeTitle()
    {
        Book.Title = "New title";
    }
}

public class Book
{
    public string Title {get;set;}
    public List<Chapter> Chapters {get;};
}

public class Chapter
{
    public string ChapterTitle {get;}
    public string Content {get;}
}


Now if I try to update a property of "Book" like in ChangeTitle or AddChapter methods, the view doesn't update.

I guess ObservableProperty only works when assigning a new value directly to the tagged property. Because my LoadBook method can definitely update the view. I'm binding my view like this:

<TextBlock Content="{Binding Book.Title}" />
<ListBox ItemsSource={Binding Book.Chapters}>
    <TextBlock Content="{Binding ChapterTitle}" />
    <TextBlock Content="{Binding Content}" />
</ListBox>


How can I make it so that updating the inner properties of Book also updates the Book property itself?

Or maybe I shouldn't use the Book object directly and I should just expose the Book properties directly in the viewmodel like this below?
public partial class MyViewmodel : ObservableObject
{
    [ObservableProperty]
    private string title;

    [ObservableProperty]
    private ObservableCollection<Chapter> chapters;

    // ...
}
Was this page helpful?