简体   繁体   中英

Extending a UserControl

I would like to extend a usercontrol by another user control.

Say I have a user control A - Which displays text - "Control A"

User control B : A and displays "Control B".

When I load user control B, dynamically, only "Control B" is written on the page.

Im using the following code to load them dynamically:

B myControl = (B)Page.LoadControl("~/UC/B.ascx");
myPage.Controls.Add(myControl);

Here's the code for the user control B:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="B.ascx.cs" Inherits="A" %> 
<div>Control B</div>

Any ideas, what I might be doing wrong?

For simple controls like in your example, composition is often a better solution than inheritance. Consider having control B contain an instance of control A inside it:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="B.ascx.cs" Inherits="B" %> 
<%@ Register TagPrefix="My" TagName="ControlA" Src="A.ascx" %>
<My:ControlA runat="server" />
Control B

Come to think of it, I've never tried to use inheritance with ascx controls and I don't even know what you would expect it to do. Events and virtual functions make sense in the context of inheritance, but how should the contents of the designers be merged?

If you want to define insertion points in the base control, there seemt o be two natural ways to do it. I've only used PlaceHolder members in the context of Master pages, but maybe you could make use of them in a user control. On the other hand, it's always possible to dynamically insert an object into the Controls collection or as a child of an existing control.

// class A
public void AddMyControl(Control c)
{
    mydiv.Controls.Add(c); // mydiv is defined in the designer
}

// somewhere else - maybe in the page?
theControl.AddMyControl(Page.LoadControl(thePath));

You must add

A other = (A)Page.LoadControl("~/UC/B.ascx");
myPage.Controls.Add(other);

Or encapsulate your control A in control B , and in the Code Behind of your control B , add the same code in order to load control A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM