加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何从另一个UserControl继承UserControl?

发布时间:2020-12-16 03:29:01 所属栏目:asp.Net 来源:网络整理
导读:是否可以从另一个用户控件继承用户控件? 我想要实现的是从另一个用户控件继承的用户控件.所以我有baseusercontrol.ascx,这只是文本“Stuff”.然后我有另一个用户控件,childusercontrol.ascx从baseusercontrol.ascx继承.如果我没有在childusercontrol.ascx中
是否可以从另一个用户控件继承用户控件?

我想要实现的是从另一个用户控件继承的用户控件.所以我有baseusercontrol.ascx,这只是文本“Stuff”.然后我有另一个用户控件,childusercontrol.ascx从baseusercontrol.ascx继承.如果我没有在childusercontrol.ascx中更改任何内容,我希望baseusercontrol.ascx文本显示“Stuff”.

而且我应该能够扩展派生的基本用户控制功能.

我也试过像this这样的东西,但在我的情况下还不够.

现在我的childusercontrol.ascx看起来在下面

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="childusercontrol.ascx.cs" Inherits="test_childusercontrol" %>
<%@ Register src="baseusercontrol.ascx" tagname="baseusercontrol" tagprefix="uc1" %>

childusercontrol.ascx.cs如下

public partial class test_childusercontrol : baseusercontrol
{
    protected void Page_Load(object sender,EventArgs e)
    {

    }   
}

当我浏览此页面时,我得到错误

Object reference not set to an instance of an object.
Description : An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details : System.NullReferenceException: Object reference not set to an instance of an object.

任何线索?

解决方法

我已经为自己测试了这种情况.实际上,您不能从具有自己的ASCX代码的UserControl的基类继承.

但是,你可以做的是在(可能是抽象的)基类(没有ASCX)中实现一些基本功能,如下所示:

public class BaseClass:UserControl
{
    public String BaseGreeting { get { return "Welcomebase!"; }}
}

然后在具有自己的ASCX文件的具体UserControl类中使用此基类的方法和属性.

public partial class childusercontrol : BaseClass
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        Greeting = base.BaseGreeting; //As initial value
    }
    public String Greeting
    {
        get { return LabelGreeting.Text; }
        set { LabelGreeting.Text = value; }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读