How do you get a reference to the ViewModel from the View?

Topics: Conventions, Getting Started
May 25, 2011 at 6:25 PM

I'm trying to databind the Bing map control to the ViewModel in a Windows Phone project. The map is able to pick up an (object) property value from the ViewModel to assign to the Map.Center object, but for some reason, the map is not able to assign the value back to the object reference on the ViewModel. IOW, Mode=TwoWay isn't working. The object in question is basically a point with Latitude and Longitude properties. I'm binding the Map.Center object to the ViewModel.Center object. I know that most databinding is to a property of the ViewModel of primitive type, but I was not able to find a way to bind the individual Lat/Lng properties of the Map.Center object to primitive properties on the ViewModel.

Anyway, that's just the back story. What I'd like to find out is if there's a way to get a reference to the ViewModel from the View so that I may programmatically assign values to the ViewModel from the code behind. I know it's ugly, but I have no choice if the databinding doesn't work. I tried casting the View.DataContext to the type of the ViewModel within the View's code behind, but that always returned a null reference. My workaround was to override the Screen::OnViewLoaded() method and then have the ViewModel pass a reference of itself to the View. While this works perfectly fine, it feels like an ugly workaround that skirts the reason to use the MVVM pattern in the first place.

Coordinator
May 25, 2011 at 6:46 PM

You should be able to cast the DataContext. You may have been trying to do this too early. You will need to do it after the view is Loaded at least.

May 25, 2011 at 6:50 PM

OK. I'm now able to get a reference to the ViewModel through the View.DataContext property. I must have tried to get the reference in the View's constructor the first time around. I grabbed the reference in the PhoneApplicationPage_Loaded() method, and it now works.

I'm still puzzled by why the TwoWay databinding isn't working.

May 25, 2011 at 6:52 PM
Edited May 25, 2011 at 6:53 PM
EisenbergEffect wrote:

You should be able to cast the DataContext. You may have been trying to do this too early. You will need to do it after the view is Loaded at least.


Yup. I found this out just a few minutes ago. :)

So should two-way databinding to object references work in Silverlight/WP7?