开发者

Entity Framework - Binding Navigation Property to ListBox

开发者 https://www.devze.com 2023-02-12 00:40 出处:网络
I\'m working with MVVM and the Entity Framework. I have an entity called \"Quote\" with a navigation property called \"QuoteProducts\" which contains all the products in the quote.

I'm working with MVVM and the Entity Framework. I have an entity called "Quote" with a navigation property called "QuoteProducts" which contains all the products in the quote.

My ViewModel has a property called "CurrentQuote" which is of type "Quote" and my view has the following ListBox:

<ListBox ItemsSource="{Binding CurrentQuote.QuoteProducts}">

Works out great, for the most part. I load a quote, the ListBox fills up and everything is super. However, when I add a new product using

QuoteProduct product = new QuoteProduct();
product.Product = SelectedProduct;
CurrentQuote.QuoteProducts.Add(product);

the new product does not开发者_JAVA百科 appear in the ListBox. I've been doing some reading and it looks like the reason is because the collection behind the navigation property isn't notifying the UI that it has changed. But what I didn't find was a clean way to make it do just that.

I saw one solution that required keeping a separate list of the QuoteProducts, bind to that, and add to both of them when I add a product, but that doesn't seem like the right way to go.

Is there any way that I can tack on functionality to my data model to have it notify when the collections get changed?


No there isn't, you'll have to modify the declaration of CurrentQuote.QuoteProducts to a class that implements INotifyCollectionChanged. The reason behind that is simple - WPF doesn't watch the CurrentQuote object, but the CurrentQuote.QuoteProducts collection directly.


The easiest method I use is instead of binding to ObservableCollection directly, use ICollectionView. Still use ObservableCollection as the underlying ICollection but it doesn't raise all the events the UI needs. I actually try to use IBindingList instead of OC in WPF because OCs never raise updated events when the collection is updated from the UI, you can only know when something is added or removed. That isnt totally true as you can listen for individual item property updates but it abstracts it to far away for my liking.
The only place I really use ObservableCollection is in Silverlight/WP7 because there's no other choice. They do make more sense to use when the UI is a dumb view & everything is added via the VM though but that is rare for me.


The EntityObservableCollection might help in your scenario. The code for this collection and a code example can be found in the BookLibrary sample application of the WPF Application Framework (WAF).

0

精彩评论

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