Get and cast Masterpage UserControl from Content Page to access specific UC Property

前端 未结 2 1405
时光取名叫无心
时光取名叫无心 2021-01-23 06:20

I have a MasterPage (MyBoxx.Master) referencing 2 usercontrols :

<%@ Master Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"MyBoxx.master.cs\" Inherits=\"         


        
2条回答
  •  清歌不尽
    2021-01-23 06:35

    Depending on how you have your User Control coded you may or may not be able to access all it's properties/methods when exposing it to the master page as a master page property..

    Here is a solution that works:

    In your master page you need to register your user control (.ascx) and place it on the master within the form tag.

    Register the User Control

    <%@ Register Src="~/Controls/MyUserControl.ascx" TagPrefix="uc" TagName="MyUserControl" %>
    

    Add the User Control to the Master Page

    ...

    Now for the content page, you must create a reference in each of the content pages that use the master page for which you want to use the control.

    Add the Reference in the content Page

    <%@ Reference Control="~/Controls/MyUserControl.ascx" %>
    

    Now you can setup a public variable at the page level and access it's properties/methods

    Partial Class MyPage

      Inherits System.Web.UI.Page
    
      Public usrCtrl As MyUserControl
    
    
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    
        If Master.FindControl("ucMyUserControl") IsNot Nothing Then
            usrCtrl = CType(Master.FindControl("ucMyUserControl"), MyUserControl)
            usrCtrl.ExecMyMethod()
        End If
        ...
    

提交回复
热议问题