天天看點

嵌套母版頁中的控件通路

嵌套母版頁中的控件通路很别扭。

如果一個内容頁對應一個沒有嵌套的母版頁,通路這個母版頁上的控件衆所周知:類似(Button)Page.Master.FindControl("Button1")

可是這個母版頁如果又嵌套在另一個母版頁裡面,上述語句包你什麼東西都通路不到。

假設頂層母版頁 master0.master 有

        <asp:contentplaceholder id="SubMaster" runat="server">

        </asp:contentplaceholder>

子母版頁 master1.master 有

<asp:Content id="SubMasterList" ContentPlaceholderID="SubMaster"runat="server">    

<asp:contentplaceholder id="Main" runat="server">

    </asp:contentplaceholder>

<asp:Button ID="Button1" runat="server" Text="Button"/>

</asp:Content>

現在内容頁 content.aspx 結合子母版頁 master1.master,有

<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">

</asp:Content>

這時不論是

(Button)Page.Master.FindControl("Button1")

還是

ContentPlaceHolder direcMaster = (ContentPlaceHolder)Page.Master.FindControl("SubMaster");

Button b1 = (Button)direcMaster.FindControl("Button1");

都無法通路到這個 BUTTON。

我折騰來折騰去,最後才知道正确的寫法是:

ContentPlaceHolder direcMaster = (ContentPlaceHolder)Page.Master.Master.FindControl("SubMaster");

Button b1 = (Button)direcMaster.FindControl("Button1");

就是說,如果母版頁嵌套多少層,Master 就應該寫多少個。

這樣子的話,我認為如果想通路母版頁的控件,還不如通過在母版頁設定屬性來間接通路該控件。一方面,通路友善;另一方面,可屏蔽細節,内容頁根本不用關心所用的母版頁到底嵌套了多少層。