Search code examples
windows-phone-7xamldata-bindingbindingdatatemplate

Binding to value in parent page from in usercontrol in listview datatemplate in Windows Phone 7


I have a ViewCharacter page that has a View Model (CharacterViewModel) as its DataContext, in that CharacterViewModel I have an ObservableCollection of WeaponViewModel that a ListBox is using as an ItemSource. The ListBox's DataTemplate contains a UserControl that is designed for the WeaponViewModels in the parent page's View Model's ObservableCollection. I need to bind a CommandParameter of a button in the UserControl to a property on the Parent page's view model (CharacterViewModel). I've tried using {Binding DataContext.TargetProperty, RelativeSource={RelativeSource TemplatedParent}} with no success and am at a loss of what to do without outright breaking all MVVM patterns.


Solution

  • Windows Phone 7 lacks a relative source binding. I have created a Silverlight implementation here:

    http://www.scottlogic.co.uk/blog/colin/2009/02/relativesource-binding-in-silverlight/

    But for WP7, where performance is critical, I would avoid using it!

    I would instead recommend making the relationship between CharacterViewModel and WeaponViewModel bi-directional. In other words, add a Parent property to WeaponViewModel which will be a reference to the owning CharacterViewModel. You can then bind to properties on CharacterViewModel via this property.