2011-06-16 40 views
3

我得到了一個像這樣從其用戶控件調用父頁面方法的方法。此「DisplayMessage」函數只接受字符串變量消息並將其顯示在屏幕上。 在用戶控件中,我放置了一個文本框和一個按鈕。在Button的click事件上,我調用上面討論的使用Reflection的父頁方法,並將文本框的值傳遞給方法,然後調用該方法,並將消息顯示在屏幕上。從其父頁面調用UserControl方法

父頁:

public void DisplayMessage(string message) 
{ 
    Response.Write(message); 
} 

用戶控制:

protected void btnSend_Click(object sender, EventArgs e) 
{ 
    this.Page.GetType().InvokeMember("DisplayMessage",System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { txtMessage.Text }); 
} 

它工作正常的我。

現在我需要的是,我必須從它的父頁面調用一個存在於UserControl中的方法。

請給我建議。提前致謝。

回答

5

無論您將ID=""屬性設置爲何時將控件放在頁面上,都可以使用變量名稱在頁面內引用它。

所以,如果你的頁面看起來是這樣的:

<my:UserControl runat="server" ID="myControl" /> 

然後,你可以這樣做:

myControl.MyControlMethod() 

的方法,從父用戶控件被調用必須是公共的。如果它是私人或受保護的,則不能從父級調用該方法。

此外,而不是通過反射調用頁面功能,you might be better off using events

0

this.Page會給你一個頁面對象的引用。

如果在基本頁面中實現DisplayMessage,然後繼承它。

你可以施放this.Page作爲BasePage的,然後調用方式:)

if(this.Page is BasePage) 
{ 
    BasePage bs = this.Page as BasePage 

    bs.DisplayMessage(....) 
} 
0

我想我找到了最簡單辦法做到這一點

方法只是通過的參考在用戶控件的構造函數中的父級。

this.animationControl = new VideoEditor.AnimationControl(this); 

並且在用戶控制的構造節省母體形式在本地變量的參考

public AnimationControl(Form1 form) 
{ 
     _form1 = form; 
     // other initialization stuff 
} 

現在通過這個局部變量「_form1」

訪問來自父類的任何

_form1.MessageFromAnimationControl(choosenAnim); 

訪問父項變量/子項中的方法或將子變量發送給父項。我希望它會幫助別人:)