1
votes

I have a main window coupled with a view model.This main window uses a usercontrol which also has its own viewmodel.

What I would like to achieve is setting a binding in the main window's xaml between one of its viewmodel's custom property and one of the usercontrol's viewmodel's custom property.

How would one go about doing that?

3
You should avoid having your view connect 2 VM. Views are meant to be disconnected as much as possible in MVVM. If you can access the child VM in the parent VM, Keep the properties in sync via the parent VM or use something like the Messenger from MVVM light to communicate between 2 independant VM'sViv

3 Answers

1
votes

Could you instead use the ViewModels as projections of a Model?

That is, could you have a class that holds the state (or actions) that both the VMs need to expose and have both the VMs reference this class?

If for some reason you have to couple views to something outside their own DataContext I believe you can only go up the visual tree by using RelativeSource FindAncestor in the binding. I don't think you can traverse down (e.g. Window -> Control).

0
votes

If you really want to Bind them together you could make your ViewModel's properties Dependency Properties and your ViewModel derive from DependencyObject - then you could do..

 var binding = new Binding("Something");
 binding.Source = myViewModel1;
 binding.Mode = BindingMode.TwoWay;
 BindingOperations.SetBinding(viewModel2,ViewModelType.SomethingProperty,binding);

If this is a good design having your viewmodels derive from DependencyObject is another question..

You could also try looking at this library that allows binding to and from POCOs.

0
votes

I ended up not using a modelview for my usercontrol, not as neat but at least it works and is less complicated datacontext wise. Thanks to all.