Binding between master and detail

Aug 17, 2010 at 3:22 AM
I was wondering how to bind something from the master page that contains (ContentControl) a child view model. For example, a listbox in the master view having the selected item bound (one way) to a property on the child view model. In a similar scenario, how would I be able to bind a view directly against the same the view model selected into that listbox. I see the need for these two types of bindings: bind Master.ListBox.SelectedItem ==> Child.ItemToWorkOn bind Master.ListBox.SelectedItem ==> Master.ChildView I have solved it using a property in the master view model bound to selected item, and then setting the value and/or use the event aggregator, but thought this might be a common enough scenario to use a binding.
Aug 17, 2010 at 9:27 AM
Edited Aug 17, 2010 at 9:32 AM

The solution of using the master VM to dispatch the change in listbox selection to child VMs seems pretty fine to me, because gives the master the responsibility to deal with different structures and behaviors of child VMs. Yet, for simple scenarios, the binding is more straightforward.
You should be able to achieve "Master.ListBox.SelectedItem ==> Child.ItemToWorkOn" binding with something like:

 

public class MasterVM {
	public IChild Child {get{...} set{...}}
}

public interface IChild {
	object ItemToWorkOn {get; set;}
}

public interface ChildVM: IChild {
	public object ItemToWorkOn {get{...} set{...}}
}

 

 

<!--MasterView.xaml-->
<ListBox SelectedItem="{Binding Child.ItemToWorkOn}" ItemsSource="..."/>
<ContentControl cal:View.Model="{Binding Child}" />

 

The interface is not really necessary, since binding engine just navigate property paths on concrete classes, but helps to enforce the convention in children. Make sure that properties raise changhe notifications.


For "Master.ListBox.SelectedItem ==> Master.ChildView" binding, something like this should work:

 

<ListBox Name="theList" ItemsSource="..."/>
<ContentControl cal:View.Model="{Binding ElementName=theList, Path=SelectedItem}" />

 

You have to ensure that each different class in the items collection of the ListBox has a corresponding view, so that CM could pick up the view correctly when cal:View.Model is changed through the binding.