直接从ascx设置代码隐藏公共属性

And*_*ndy 3 c# asp.net user-controls

我有三个用户控件:usercontrolA,usercontrolB以及usercontrolC所有共享相同的代码隐藏每个都具有:

<%@ 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中添加一个脚本标签来设置ShowAll Page_Load:

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

但是想要保留Page_Load我已经在代码隐藏中实现的实现. 有没有其他方法为usercontrolB自动设置此属性?

编辑:如果有可能我希望能够在ascx而不是后面的代码中设置它,以便后来的其他人可以为所有实例添加usercontrolD并设置ShowAll为true,usercontrolD而无需让我修改和重新编译代码隐藏.

Muh*_*tar 5

您必须在usercontrol类构造函数中设置它.

public ConstructorClassName()
    {
       ShowAll = true;
    }
Run Code Online (Sandbox Code Playgroud)

这是完整的代码示例...

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)
  {
  }
}
Run Code Online (Sandbox Code Playgroud)

我将默认值设置为true,但您也可以传递添加此用户控件的值.例如

<uc1:usercontrolB ID="usercontrolB1" runat="server" ShowAll="false" />
Run Code Online (Sandbox Code Playgroud)

调用它时,它将覆盖值 false