直接从Ascx设置代码隐藏公共属性 [英] Set codebehind public property directly from ascx

查看:67
本文介绍了直接从Ascx设置代码隐藏公共属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个用户控件: usercontrolA usercontrolB usercontrolC ,它们都共享相同的代码,分别具有:

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

<%@控制语言="c#" AutoEventWireup ="True" Codebehind ="usercontrolA.ascx.cs" Inherits ="usercontrolA" TargetSchema ="http://schemas.microsoft.com/intellisense/在ascx顶部的ie5%> .

在代码隐藏文件中,我有一个名为 ShowAll 的公共属性.

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"/>

但是我希望在usercontrolB上将ShowAll始终设置为true ,所以宁愿不必每次将ShowAll放在页面上时都将其设置.

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.

我知道我可以向usercontrolB添加脚本标记以在 Page_Load 中设置ShowAll:

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>

但是要保留代码中已经存在的 Page_Load 实现.还有其他方法可以为usercontrolB自动设置此属性吗?

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?

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

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.

推荐答案

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

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

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

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" />

调用此方法时,它将值覆盖为 false

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

这篇关于直接从Ascx设置代码隐藏公共属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆