从Silverlight中的一个子用户控件调用父用户控件的方法 [英] Calling parent UserControl method from a child UserControl in Silverlight

查看:168
本文介绍了从Silverlight中的一个子用户控件调用父用户控件的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#Silverlight应用程序。此应用程序具有一个2x2格一个用户控件。网格的每个单元都有它自己的用户控件。每个子用户控件元素都有一个按钮。当用户点击这个按钮在一个孩子,我想执行的是父用户控件的方法。该方法然后将信息发送到其他三个孩子用户控件。我该怎么做呢?

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?

感谢您!

推荐答案

如果您正在使用的绑定,可以将模型到主控制的DataContext绑定,如下面的模型:

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(){ //... }
}

然后在每个孩子的控制,因为它的DataContext的是继承从父主用户控件的绑定的DataContext:

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.

这篇关于从Silverlight中的一个子用户控件调用父用户控件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆