2010-07-23 59 views

回答

2

一个用户控件应该是可重复使用,因此要正确地做到这一点,你应该使用一个事件从用户控件的页面钩到,即:

public NewTextEventArgs : EventArgs 
{ 
    public NewTextEventArgs(string newText) 
    { 
     _newText = newText; 
    } 

    public NewText 
    { 
     get { return _newText; } 
    } 
} 

然后将下面的事件添加到您的用户控件:

public event OnNewText NewText; 
public delegate void OnNewText(object sender, NewTextEventArgs e); 

然后火从用户控件的事件:

private void NotifyNewText(string newText) 
{ 
    if (NewText != null) 
    { 
     NewText(this, new NewTextEventArgs(newText)); 
    } 
} 

然后强制牛逼消耗你的网页,事件和用户控件和页面不再紧密耦合:

然后处理该事件和文本设置为您的标签:

protected void YourControl1_NewText(object sender, NewTextEventArgs e) 
{ 
    Label1.Text = e.NewText; 
} 
+0

@Nathan Taylor - 我删除了最初的答案,并换成了更好的事件驱动的答案。 – GenericTypeTea 2010-07-23 08:55:30

+0

好东西!只是一个快速提示,通用EventHandler 不再需要为您的自定义eventargs类创建委托。你可以简单地做'公共事件EventHandler NotifyNewText;' – 2010-07-23 16:41:14

+0

@Nathan - 谢谢。我不知道! – GenericTypeTea 2010-07-23 18:12:59

2

你最好的选择是使用某种事件来通知UserControl已更新的包含页面。

public class MyControl : UserControl { 
    public event EventHandler SomethingHappened; 

    private void SomeFunc() { 
     if(x == y) { 
      //.... 

      if(SomethingHappened != null) 
       SomethingHappened(this, EventArgs.Empty); 
     } 
    } 
} 

public class MyPage : Page { 

    protected void Page_Init(object sender, EventArgs e) { 
     myUserControl.SomethingHappened += myUserControl_SomethingHappened; 
    } 

    private void myUserControl_SomethingHappened(object sender, EventArgs e) { 
     // it's Business Time 
    } 
} 

这仅仅是一个基本的例子,但我个人建议使用设计器界面来指定用户控件的事件处理程序,以便分配获取你的设计师处理的后台代码,而不是一个你的工作英寸

+0

我认为是这样,但是如何在我的页面上捕获此事件? – Tony 2010-07-23 08:49:42

0

您可以使用页面属性来访问页面包含用户控件的。请尝试:

((Page1)this.Page).Label1.Text =“Label1 Text”;