0

I have a C# Silverlight application. This application has a UserControl with a 2x2 Grid. Each cell of the Grid has a UserControl of it's own. Each of these child UserControl elements has a Button. When a user clicks the Button in a child, I want to execute a method that is in the parent UserControl. This method then sends information to the other three child UserControls. How do I do this?

Thank you!

user70192
  • 13,786
  • 51
  • 160
  • 240

2 Answers2

0

If you are using binding, you could bind a model to the DataContext of the master control such as the following model:

class MasterViewModel{

  ///Action for child user control 1
  void DoUserControlAction1(){ //... }

  ///Action for child user control 2
  void DoUserControlAction2(){ //... }

  //...
  ///Action for child user control n
  void DoUserControlActionN(){ //... }
}

Then in each child control, since its DataContext is inherited from the bound DataContext of the parent Master UserControl:

class UserControl1{
  public void HandleButtonClick(object sender, EventArgs e){
    ((MasterViewModel) DataContext).DoUserControlAction1();
  }
}

This kind logic should be in the ViewModel that you have bound to the master control.

If you do not have binding, you could always add events to the child controls and bubble them up to the master control and handle it there.

Sheldon Warkentin
  • 1,706
  • 2
  • 14
  • 31
  • Hi Sheldon, while my parent control does have a ViewModel, I want to do some UI logic in the parent control as well. For this reason, I was hoping to actually execute a method in the Parent.xaml.cs. Is there a way to do this from a child control? – user70192 Mar 28 '11 at 14:39
  • In that case, your best bet is to add events to your child controls that are subscribed to in Parent.xaml.cs. So, when you click on the button in your child control, your event is fired and handled in the parent control; which can then call the method you are interested in. – Sheldon Warkentin Mar 28 '11 at 14:49
  • Though, another option would be to pass a delegate from Parent.xaml.cs to your children for them to call. ie: childControl.ParentMethodToCall( () => someParentMethod() ); So, passing an Action to the child control that gives it a delegate so that it can call the parent method, which in tern calls its internal method. – Sheldon Warkentin Mar 28 '11 at 14:51
0

If you were using PRISM you could use the EventAggregator or the messaging pattern in MVVMLight to pass messages from the child userControls VMs to the parent control VM.

This type of separation could help encapsulate the dependencies between the controls.

Rus
  • 1,827
  • 1
  • 21
  • 32