A bug with ViewModel first approach

I found something interesting last week.

I was using typical viewmodel first approach. Had a DataTemplate defined in my Resource Dictionary and a view referenced inside it. Then had a collection of typeof(viewmodel) bound to the itemscontrol on view(tab control in this case). All worked fine. Then suddently i noticed something. After creating few tabs, some textboxes on each tab were simply mirroring each other. So if i type “abcd” on one textbox on first tab, that same textbox on second tab was also showing “abcd” text. I found this weird because I always thought that when i add a new item in the collection from the viewmodel, it will create a new instance of the childviewmodel(which is bound to each item of the list) and hence, also create a new instance of the view. This was happneing. I checked ReferenceEquals() and they were indeed different object. So why was this happening as if they were the same objects?

I also checked that I was not registering them as Singletons in Unity.

Finally, we found the culprit. It was the missing bindings. It seems that with ViewModel first approach, you are supposed to make sure that all the controls on the view are bound to some property on the respective ViewModel. If not, then they will simply mirror each other and depict the behaviour i explained above.

I did one more test. I kept three textboxes on the view. First with binding, second without binding, and third with binding but no public property actually defined by that name on the view model. What i found is this:

  1. The first textbox with binding, behaved as expected. Each maintained its own state and didn’t interferce or influence any other controls on other views on seperate tabs
  2. The second textbox always mirrored with other views on the tab contor. Any view on a tab with that textbox will kind of sync up with same textboxe on same view on another tab
  3. The third texbox kind of behaved opposite of second. Because of missing valid bindings, no matter what you type, the moment you switch between tabs, the value will vanish on for same textbox on all views on all tabs

So make sure you don’t forget to bind all your controls on the view if you are using the ViewModel first approach. So this is a second issue with using ViewModel first apporach, the first being that the same viewmodel can’t be used for different views.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s