开发者

Trouble in MVVM with listbox refreshing

Ok, learning MVVM drives me mad. I know it's good pattern, I know, but sometimes...

I have simple book cataloging app. Model done with EF code first. It contains two tables authors and books. Now, I have MainWindow with MainWindowViewModel behind it. In MainWindow I have a Listbox bound to ViewModel like this:

<ListBox ItemContainerStyle="{DynamicResource ListBoxItemStyle1}"
ItemsSource="{开发者_JAVA百科Binding Authors, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
DisplayMemberPath="Fullname"Name="AuthorsListBox" sSynchronizedWithCurrentItem="True"/>

Where "Authors" is ObservableCollection<Author> in my DataContext (ViewModel). Everything seems fine for now. What is wrong is:

I'm opening new window, simple as hell, only two textboxes and button to create new author

After validation I click the button and new Author entity is saved to database. Then, I close "CreateAuthorWindow" and back in MainWindow.

There is new no entity showing in listbox. And I can't get it show! Everything in my model implements INotifyPropertyChanged. Is there any way to do this without refreshing by hand? (which actually doesn't work either...)


After validation I click the button and new Author entity is saved to database. Then, I close "CreateAuthorWindow" and back in MainWindow.

Saving the new Author to the database will not be enough, you will need to either A) reload Authors from the database or B) add the newly created Author object to the existing list.


To get the new Author to show up in the list box, you need to make sure:

  • The DataContext for the ListBox is set. If you have set your ViewModel as the DataContext of the View then that will be fine.
  • The Authors property must be public, and must raise a NotifyCollectionChanged event when the collection is changed (items are added or removed). An ObservableCollection<T> will do this for you.
  • The new author object you create gets added to the Authors collection. This should raise the NotifyCollectionChanged event, and the View should refresh.

If you are doing all these things and still not seeing the new item turn up, check for binding errors in your debug window.

If it's still not working, you may need to post some code...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜