alerya
alerya

Reputation: 3175

WPF MVVM pattern ObservableCollection

due to the mvvm pattern Model shouldn't know anything about ViewModel.

What if I create a ListBox Field in one of my Model. Looks well and right. But next step I have to tie this value to the ObservableCollection in ModelView.

I can do this:

var myCollection = new ObservableCollection (myList);

But in this case I lost of all advantages for OC. THis collection made static and neither inserts or updates reflects in my View tied to this collection.

Any thoughts ?

Upvotes: 1

Views: 1681

Answers (2)

Sheldon Warkentin
Sheldon Warkentin

Reputation: 1746

When you call

var myCollection = new ObservableCollection (ListBox)

You are copying the values of myList into the ObservableCollection. Nothing here will update ListBox list.

If this is the desired effect, and you may want to update your ViewModel with:

///...
var myCollection = new ObservableCollection (ListBox)
myCollection.CollectionChanged += (sender, args) => RefreshListBox(myCollection);
///...
private void RefrehListBox(ObservableCollection<...> collection){
 //Refresh ListBox with collection
}

This way, every time the ObservableCollection updates, you synchronize the underlying model with the changes.

Upvotes: 1

pluka
pluka

Reputation: 125

You normaly use an ObservableCollection because it automatically updates the interfaces. I think you are doing something in a wrong way. In your ViewModel you have the ObservableCollection with a list of elements, you can initialize it with a normal list o an array of elements. You shouldn't initialize your OC with your ListBox. After you have to bind it in your view. When you add an element in you OC the view will update.

Upvotes: 2

Related Questions