簡體   English   中英

直接從ascx設置代碼隱藏公共屬性

[英]Set codebehind public property directly from ascx

我有三個usercontrols: usercontrolAusercontrolBusercontrolC它們共享相同的代碼隱藏,每個代碼都有:

<%@ Control Language="c#" AutoEventWireup="True" Codebehind="usercontrolA.ascx.cs" Inherits="usercontrolA" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>頂部ascx。

在codebehind文件中,我有一個名為ShowAll的公共屬性。

我知道我可以在將usercontrol放在頁面上時設置此屬性,例如

<uc1:usercontrolB ID="usercontrolB1" runat="server" ShowAll="true" />

但是我希望ShowAll始終在usercontrolB上設置為true,所以不必每次將它放在頁面上時都要設置它。

我知道我可以向usercontrolB添加一個腳本標簽,以在Page_Load設置ShowAll:

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e)
    {
        ShowAll = true;
    }
</script>

但是想要保留我在代碼隱藏中已經擁有的Page_Load實現。 有沒有其他方法為usercontrolB自動設置此屬性?

編輯:如果有可能我希望能夠在ascx而不是后面的代碼中設置它,以便后來的其他人可以添加usercontrolD並為所有usercontrolD實例將ShowAll設置為true,而無需讓我修改並重新編譯代碼隱藏。

您必須在usercontrol類構造函數中設置它。

public ConstructorClassName()
    {
       ShowAll = true;
    }

這是完整的代碼示例...

public partial class WebUserControl : System.Web.UI.UserControl
{
  public WebUserControl()
  {
    ShowAll = true;
  }
  private bool _showAll;
  public bool ShowAll
  {
    get { return _showAll; }
    set { _showAll = value; }
  }   

  protected void Page_Load(object sender, EventArgs e)
  {
  }
}

我將默認值設置為true,但您也可以傳遞添加此用戶控件的值。 例如

<uc1:usercontrolB ID="usercontrolB1" runat="server" ShowAll="false" />

調用它時,它會將值覆蓋為false

在您的代碼中,您可以檢查實例類型:

protected void Page_Load(object sender, System.EventArgs e)
{
    if (this is usercontrolB) 
    {
         ShowAll = true;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM