2013-02-26 72 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 
相关问题