Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Binding Navigation Property to ListBox

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 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?

like image 844
Anthony Compton Avatar asked Nov 06 '22 02:11

Anthony Compton


1 Answers

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.

like image 93
Femaref Avatar answered Nov 15 '22 05:11

Femaref