Usercontrol Interaction

Mar 31, 2011 at 5:41 PM

Hi!

I'll start with the scenario:

I have a WindowView with a ViewModel;
The WindowView contains a UsercontrolView which also has a ViewModel.

Now I would like to bind f.e. a Textbox.Text on the WindowView with a Textbox.Text on the UsercontrolView..

 

What's the best way to accomplish this with MVVM Light?

 

Coordinator
Mar 31, 2011 at 6:52 PM

Hi,

Multiple ways:

  • Have your WindowViewModel be the DataContext of both the WindowView and the UserControlView. Then bind both TextBoxes to the same property on the WindowViewModel.

This works well if your UserControlView does not have many UI elements, so if it is not worth making a separate VM for that view.

  • Have two viewmodels. UserControlViewModel is exposed as a property on MainViewModel. Still set the DataContext of both WindowView and UserControlView to MainViewModel. Then, do the TextBox.Text binding to the same property on MainViewModel, but all other properties on UserControlView are bound for example to MyUserControlVM.MyProperty.

This was UserControlViewModel is a child of MainWindowViewModel, which allows you to separate the responsibilities, have smaller objects, etc...

  • Have two viewmodels. They do not know each other. When the property on the first changes, use the Messenger class to send a message with the new value. In the second VM, receive the message and set another property with the same value.

Which solution you choose depends on a number of factors, such as size of the VMs, configuration of the UI, etc.

Cheers,

Laurent

 

 

Mar 31, 2011 at 8:10 PM

Thank you very much for your Answer!

I have sent the Window's control through a message to the Usercontrol, and used SetBinding to bind its property to another control =D

Again, thanks!