简体   繁体   中英

WPF MVVM Caliburn Micro - Notify property on ViewModel from another ViewModel

I have two views

  • Overview-View: Contains of a datagrid which is binded to a IObservableCollection (the items get loaded from a repository (xml file) in the constructor)
  • Add-View: Contains of some textboxes and a button which adds an item to the repository

    What I want now is to notify the IObservableCollection of the Overview-View that an item was added to the xml file.

My first try was the following:

public IObservableCollection<Book> BookList
{
    get
    {
        this.LoadBookList();
        return this.bookList;
    }
    set
    {
        this.bookList = value;
        this.NotifyOfPropertyChange(() => this.BookList);
    }
}

this.LoadBookList() initializes this.bookList from the repository.

This worked of course (the item is added in the xml file so the repository get it and sets the booklist), but there is the following problem:

I do also have a Delete-Button at each row of the datagrid which is binded to DeleteItem(Book book)

public void DeleteItem(Book book)
{
    var bookToRemove = this.BookList.Single(b => b.Equals(book));
    this.BookList.Remove(bookToRemove);

    this.BookRepository.WriteBookList(this.BookList);
}

But with the this.LoadBookList(); call in the BookList -Property, the list gets filled with all items from the repository again when calling the this.BookRepository.WriteBookList(this.BookList);

One solution would be to use the backing property this.bookList in the DeleteItem(...) -Method... but is this the right approach?

Is there a better / more beautiful / cleaner approach?

Thanks in advance

Load the list only when this.bookList is null. most probably, you will be filling bookList inside LoadBookList() . So, modify the getter to:

if(this.bookList==null)
        this.LoadBookList();
 return this.bookList;

Note : initialise booklist inside LoadBookList().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM