开发者

Set codebehind public property directly from ascx

I have three usercontrols: usercontrolA, usercontrolB and usercontrolC which all share the same codebehind each having:

<%@ Control Language="c#" AutoEventWireup="True" Codebehind="usercontrolA.ascx.cs" Inherits="usercontrolA" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %> at the top of the ascx.

In the codebehind file I have a public property called ShowAll.

I know I can set this property when I put the usercontrol on the page e.g.

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

However I would like ShowAll to always be set to true on usercontrolB so would rather not have to set it every time it is placed on a page.

I know I can add a script tag to usercontrolB to set ShowAll in Page_Load:

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

But want to keep the Page_Load implementation I already have in the codebehind. Is there any other way to set this property automatically for usercontrolB开发者_开发问答?

Edit: If it's possible I'd like to be able to set this in the ascx rather than in the code behind, so that someone else later on could add usercontrolD and set ShowAll to true for all instances of usercontrolD without needing to get me to modify and recompile the codebehind.


You have to set this in usercontrol class constructor.

public ConstructorClassName()
    {
       ShowAll = true;
    }

here is complete example with code...

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)
  {
  }
}

I set the default value to true, but you can also pass the value where you add this user control. e.g.

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

When this is called, it will overwrite the value to false


In your code behind you can check the instance type:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜