2013-02-26 44 views
3

我正在從內容頁面調用一個主頁面的共享功能。在那個共享函數中我想訪問masterpage中的一個控件,但我不知道如何。來自同一主頁面的共享功能的主頁面的訪問控制

main.master

<asp:Literal ID="ltCurrency" runat="server" /> 

main.master.vb

Partial Public Class main 
Inherits System.Web.UI.MasterPage 

Public Property CurrencyText() As String 
    Get 
     Return ltCurrency.Text 
    End Get 
    Set(ByVal value As String) 
     If value <> "" Then 
      ltCurrency.Text = value 
     End If 
    End Set 
End Property 

Public Shared Function DoSomething() As String 
    ltCurrency.Text="SOME TEXT" 'throws error: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.  

    CurrencyText="SOME TEXT" 'this property isn't found at all 

「我也嘗試實例化新的類的當前母版的: CTYPE(主,母版) .CurrencyText

End Function 


End Class 

從page1.aspx這個我稱之爲:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    main.DoSomething() 
End Sub 

我還能做什麼?

回答

4

對於它的價值(我不知道爲什麼你需要使它共享),您可以使用HttpContext獲得參考到您的網頁,並從那裏到你的主人:

Public Shared Function DoSomething() As String 
    Dim myPage = TryCast(HttpContext.Current.Handler, Page) 
    If myPage IsNot Nothing Then 
     Dim myMaster As main = TryCast(myPage.Master, main) 
     If myMaster IsNot Nothing Then 
      myMaster.ltCurrency.Text = "SOME TEXT" 'throws error: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.  
      myMaster.CurrencyText = "SOME TEXT" 'this property isn't found at all 
     End If 
    End If 
+0

事件,我想我需要做funtion共享,以便能夠從我的常規內容頁面調用它呢?如果我刪除「共享」部分,則該功能在內容頁面上不可用。 但是你的解決方案有效:) – Flo 2013-02-26 12:11:02

+0

@Floran:如果你想從內容頁面調用方法,你需要將頁面的Master屬性轉換爲你的'MasterPage'的實際類型。看看我的代碼,因爲我已經做到了。 – 2013-02-26 12:13:26

+0

啊我明白了。但是當我將它聲明爲共享方法時,我可以直接通過masterpage類名訪問方法,而不必先將其轉換爲masterpage。這裏有最佳做法嗎? – Flo 2013-02-26 12:16:33

0

第一步:在您的內容頁面中創建一個活動。

Public Event DoSomething(sender as object, myString as String) 

第二步:在您的炫魅添加事件處理程序到您剛纔在您的內容頁面創建的事件。

Addhandler contentPage.DoSomething, AddressOf ChangeCurrentText 

第3步:在處理程序中做任何你想做的事情。

Private Sub ChangeCurrentText(sender, text) 
ltCurrency.Text = text 
End Sub 

第四步:提高在內容頁

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    RaiseEvent DoSomething(ME, "BLAH BLAH") 
End Sub 
相關問題