2010-07-23 49 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」;

相關問題