0

我必须在子用户控件中使用父用户控件方法的结果。如何在子控件中找到该方法?

4

2 回答 2

11

用户控件的存在是为了让我们的代码更加可重用,用户控件可以放在任何页面中,有的页面可以有这两个用户控件,有的页面没有,所以不能保证页面有这两个用户控件。在我看来,最好的方法是使用事件。思路是这样的:子用户控件引发一个事件,放置这个用户控件的页面处理这个事件并调用父用户控件的事件,这样你的代码还是可以复用的。

因此,子控件的代码如下

public partial class Child : System.Web.UI.UserControl
{
    // here, we declare the event
    public event EventHandler OnChildEventOccurs;

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        // some code ...
        List<string> results = new List<string>();
        results.Add("Item1");
        results.Add("Item2");

        // this code says: when some one is listening this event, raises this and send one List of string as parameters
        if (OnChildEventOccurs != null)
            OnChildEventOccurs(results, null);
    }
}

而页面需要处理这个事件的发生,像这样

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // the page will listen for when the event occurs in the child
        Child1.OnChildEventOccurs += new EventHandler(Child1_OnChildEventOccurs);
    }

    void Child1_OnChildEventOccurs(object sender, EventArgs e)
    {
        // Here you will be notified when the method occurs in your child control.
        // once you know that the method occurs you can call the method of the parent and pass the parameters received
        Parent1.DoSomethingWhenChildRaisesYourEvent((List<string>)sender);
    }
}

最后是在父控件中执行某些操作的方法。

 public void DoSomethingWhenChildRaisesYourEvent(List<string> lstParam)
    {
        foreach (string  item in lstParam)
        {
            // Just show the strings on the screen
            lblResult.Text = lblResult.Text + " " + item;
        }
    }

这样,您的页面充当事件的协调者。

于 2012-10-31T11:01:02.987 回答
0

编辑

您可以创建这样的方法来获取子控件中的父控件

public ofparentcontroltype GetParentControl(Control ctrl)
{
   if(ctrl.Parent is ofparentcontroltype)
    {
     return ((ofparentcontroltype)this.Parent);
    }
  else if  (ctrl.Parent==null)
     return null;

     GetParentControl(ctrl.Parent);
}

调用方法如下

ofparentcontroltype parent = GetParentControl(this);
if(parent!=null)
 var data = ((ofparentcontroltype)this.Parent).methodtocall();

在用户控件的代码隐藏中做这样的事情

if(this.Parent is ofparentcontroltype)
{
 var data = ((ofparentcontroltype)this.Parent).methodtocall();
}

在此处查看示例: 从子控件访问父控件的方法

于 2012-10-31T10:26:43.053 回答