I want a create a custom/user control that has children.
For Example, I want my control to have the following markup:
<div runat="server" id="div">
<label runat="server" id="label"></label>
<div class="field">
<!-- INSERT CHILDREN HERE -->
</div>
</div>
and when I want to use it on a page I simply:
<ctr:MyUserControl runat="server" ID="myControl">
<span>This is a child</span>
<div runat="server" id="myChild">And another <b>child</b>
</ctr:MyUserControl>
The child controls inside my user control will be inserted into my user control somewhere. What is the best way to accomplish this?
The functionality is similar to a asp:PlaceHolder but I want to add a couple more options as well as additional markup and the such. Also the child controls still need to be able to be accessed by the page. (in the example above the page should have the myChild Control on it)
EDIT ------
It can be a template control as long as it allows me to reference the children on the page.
By default, events raised by child controls in a user control are not available to the host page. However, you can define events for your user control and raise them so that the host page is notified of the event. You do this in the same way that you define events for any class.
UserControl : A control which can reuse the Components in the Applications. The control can be defined in both Xaml and Code-Behind. CustomControl : An UserInterface element that have a distinct behavior which is said as CustomControl.
As already discussed in the preceding, a User Control does not run directly on its own. To render a User Control you must use it in an . aspx page, now let us add the User Control in the . aspx page.
To create this control, take the following steps: Create a new website. Right click the solution (not the project) at the top of the tree in the Solution Explorer. In the New Project dialog box, select ASP.NET Server Control from the project templates.
I asked something similar myself a while ago. See here.
I believe you will have to use an ITemplate as an InnerProperty:
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content
{
get
{
return _content;
}
set
{
_content = value;
}
}
private ITemplate _content;
Then override the CreateChildControls method of your control:
protected override void CreateChildControls()
{
if (this.Content != null)
{
this.Controls.Clear();
this.Content.InstantiateIn(this);
}
base.CreateChildControls();
}
What's the harm in using an ITemplate
You can combine it with your existing markup and write whatever HTML you want within the Content
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With