Control HTML rendered by CompositeControl Templated Server Controls - c#

I'm building my first custom server control which inherits from CompositeControl
The reason for the control is to be able to have a consistent content area (HTML elements) for multiple online applications that we develop.
So instead of having to constantly type out:
<div class="titleBar">
</div>
<div class="actionBar">
</div>
<div class="workspace">
</div>
the developer could add a server control as follows:
<custom:Workspace id="..." runat="server" Title="MyTitle">
<TitleBar>
Here is the title
</TitleBar>
<ActionBar>
<asp:button id="..." runat="server" Title="MyButton" />
</ActionBar>
<Content>
<asp:DataGrid id="..." runat="server" />
</Content>
</custom:Workspace>
I read the article at http://msdn.microsoft.com/en-us/library/ms178657.aspx and it works, but the problem is... I don't understand why. (Does anyone have a link to a layman's version of an article that describes how to build these kinds of server controls?)
Main thing I notice so far is that Asp.net is rendering a bunch of SPAN elements, which of course I don't want.
How does one control the HTML that the new CompositeControl is outputting?
Thanks,
Jacques
PS. Here's my code so far:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.Design;
namespace TemplatedServerControl
{
[DefaultProperty("Title")]
[ToolboxData("<{0}:Workspace runat=server></{0}:Workspace>")]
public class Workspace : CompositeControl
{
#region FIELDS
private ITemplate _TitleBarTemplateValue;
private ITemplate _ActionBarTemplateValue;
private TemplateOwner _TitleBarOwnerValue;
private TemplateOwner _ActionBarOwnerValue;
#endregion
#region PROPERTY - TitleBarOwner
[Browsable(false),
DesignerSerializationVisibility(
DesignerSerializationVisibility.Hidden)]
public TemplateOwner TitleBarOwner
{
get
{
return _TitleBarOwnerValue;
}
}
#endregion
#region PROPERTY - ActionBarOwner
[Browsable(false),
DesignerSerializationVisibility(
DesignerSerializationVisibility.Hidden)]
public TemplateOwner ActionBarOwner
{
get
{
return _ActionBarOwnerValue;
}
}
#endregion
#region PROPERTY - Title
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("[Provide the title for the workspace]")]
[Localizable(true)]
public string Title
{
get
{
String s = (String)ViewState["Title"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["Text"] = value;
}
}
#endregion
#region PROPERTY - TitleBar
[Browsable(false),
PersistenceMode(PersistenceMode.InnerProperty),
DefaultValue(typeof(ITemplate), ""),
Description("Control template"),
TemplateContainer(typeof(Workspace))]
public virtual ITemplate TitleBar
{
get
{
return _TitleBarTemplateValue;
}
set
{
_TitleBarTemplateValue = value;
}
}
#endregion
#region PROPERTY - ActionBar
[Browsable(false),
PersistenceMode(PersistenceMode.InnerProperty),
DefaultValue(typeof(ITemplate), ""),
Description("Control template"),
TemplateContainer(typeof(Workspace))]
public virtual ITemplate ActionBar
{
get
{
return _ActionBarTemplateValue;
}
set
{
_ActionBarTemplateValue = value;
}
}
#endregion
#region METHOD - CreateChildControls()
protected override void CreateChildControls()
{
//base.CreateChildControls();
Controls.Clear();
_TitleBarOwnerValue = new TemplateOwner();
_ActionBarOwnerValue = new TemplateOwner();
ITemplate temp1 = _TitleBarTemplateValue;
ITemplate temp2 = _ActionBarTemplateValue;
temp1.InstantiateIn(_TitleBarOwnerValue);
temp2.InstantiateIn(_ActionBarOwnerValue);
this.Controls.Add(_TitleBarOwnerValue);
this.Controls.Add(_ActionBarOwnerValue);
}
#endregion
#region METHOD - RenderContents(HtmlTextWriter writer)
protected override void RenderContents(HtmlTextWriter writer)
{
base.RenderContents(writer);
}
#endregion
}
[ToolboxItem(false)]
public class TemplateOwner : WebControl
{
}
}

The extra <span> elements are coming from the TemplateOwner controls because a WebControl (which TemplateOwner inherits from) renders <span> tags by default. You could change TemplateOwner to specify the tag to render:
public class TemplateOwner : WebControl
{
public TemplateOwner() :
base(HtmlTextWriterTag.Div)
{
}
}
But you don't need to create your own class to use templates. For example, you can just use Panel controls:
private Panel _TitleBarPanel;
private Panel _ActionBarPanel;
protected override void CreateChildControls()
{
_TitleBarPanel = new Panel { CssClass = "titleBar" };
_TitleBarTemplateValue.InstantiateIn(_TitleBarPanel);
this.Controls.Add(_TitleBarPanel);
_ActionBarPanel = new Panel { CssClass = "actionBar" };
_ActionBarTemplateValue.InstantiateIn(_ActionBarPanel);
this.Controls.Add(_ActionBarPanel);
}

A simpler solution us to use the PlaceHolder control.
Like CompositeControl, this is a container control.
Unlike CompositeControl however, it doesn't render any content at all - no containing or tags.
It does mean that you can't refer to the entire control programatically, like you can with a CompositeControl, but depending on what you are doing, that may not be necessary.
Each subcontrol will have a unique ID though, so you can refer to child controls programatically (deal with events etc)

Related

How do I access ASP.NET ITemplate Container Properties

I'm trying to learn how to use ITemplate for nicer custom controls. I have it mostly working but I haven't been able to figure out how to access any properties of the container from the page.
Here is my templated control:
[ParseChildren(true)]
[PersistChildren(false)]
public partial class Example : UserControl
{
private ITemplate _CustomPanelContainer;
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(CustomPanelContainer))]
[TemplateInstance(TemplateInstance.Single)]
public virtual ITemplate CustomPanel
{
get { return _CustomPanelContainer; }
set { _CustomPanelContainer = value; }
}
protected override void CreateChildControls()
{
Controls.Clear();
if (_CustomPanelContainer != null)
{
var p = new Panel();
p.ID = "CustomPanel";
Controls.Add(p);
_CustomPanelContainer.InstantiateIn(p);
}
base.CreateChildControls();
}
public class CustomPanelContainer : Panel, INamingContainer
{
private string _Test = "TESTING!";
public string TextTest
{
get
{
return _Test;
}
set
{
_Test = value;
}
}
}
}
Here is the page implementation:
<uc1:Example runat="server" ID="Example1">
<CustomPanel>
<strong>Test: </strong> <%# Container.TextTest %>
</CustomPanel>
</uc1:Example>
It is mostly working but the problem is that <%# Container.TextTest %> always returns an empty string. When I run it on the debugger, I put a breakpoint at the line inside the TextTest property of CustomPanelContainer and the breakpoint is never hit, so the property is never actually being accessed.
What am I missing here? How do I enable access to the container's public properties via <%#Container ?
I finally figured out how to make it act the way I want.
I removed ITemplate as the type of the Container and set the type as the actual type and added a DataBind() command to CreateChildControls().
Maybe not quite the correct way to do this, but it works.
Keeping the question open for a bit to see if anyone offers any critique or a better approach, since I really don't know what I'm doing here yet.
Simplified Working code:
[ParseChildren(true)]
[PersistChildren(false)]
public partial class Example : UserControl
{
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
public virtual CustomPanelContainer Template { get; set; }
protected override void CreateChildControls()
{
Controls.Clear();
if (Template != null)
{
Template.DataBind();
Controls.Add(Template);
}
base.CreateChildControls();
}
public class CustomPanelContainer : Panel, INamingContainer
{
public string TextTest
{
get { return "TESTING!"; }
}
}
}
Page Implementation:
<uc1:Example runat="server" ID="Example">
<Template>
<strong>Test: </strong><span><%# Container.TextTest %></span>
</Template>
</uc1:Example>
EDIT: This also works when needing to hide the type of the template.
i,e., the code above exposes the type of Template to allow manipulating properties of the Panel as attributes of Template, whereas the code below hides the type of Template to block manipulation of its properties.
[ParseChildren(true)]
[PersistChildren(false)]
public partial class Example : UserControl
{
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
[TemplateContainer(typeof(CustomPanelContainer))]
public virtual ITemplate Template { get; set; }
protected override void CreateChildControls()
{
Controls.Clear();
if (Template != null)
{
var p = new CustomPanelContainer();
Template.InstantiateIn(p);
p.DataBind();
Controls.Add(p);
}
base.CreateChildControls();
}
public class CustomPanelContainer : Panel, INamingContainer
{
public string TextTest
{
get { return "TESTING!"; }
}
}

UserControl with header and content - Allow dropping controls in content panel and Prevent dropping controls in header at design time

I wrote User Control (yay!). But I want it to behave as a container. But wait! I know about
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design",
typeof(IDesigner))]
Trick.
The problem is - I don't want all of my control to behave like container, but only one part. One - de facto - panel ;)
To give wider context: I wrote a control that has Grid, some common buttons, labels and functionalities. But it also has a part where the user is supposed to drop his custom buttons/controls whatever. Only in this particular part of the control, nowhere else.
Anyone had any idea?
You should do the following :
For your user control, you need to create a new designer which enables the inner panel on design-time by calling EnableDesignMode method.
For the inner panel, you need to create a designer which disables moving, resizing and removes some properties from designer.
You should register the designers.
Example
You can read a blog post about this topic here and clone or download a working example:
r-aghaei/ChildContainerControlDesignerSample
Download Zip
Code
Here is the code for different elements of the solution.
Your user control
[Designer(typeof(MyUserControlDesigner))]
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
TypeDescriptor.AddAttributes(this.panel1,
new DesignerAttribute(typeof(MyPanelDesigner)));
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Panel ContentsPanel
{
get { return panel1; }
}
}
Designer for the inner panel
public class MyPanelDesigner : ParentControlDesigner
{
public override SelectionRules SelectionRules
{
get
{
SelectionRules selectionRules = base.SelectionRules;
selectionRules &= ~SelectionRules.AllSizeable;
return selectionRules;
}
}
protected override void PostFilterAttributes(IDictionary attributes)
{
base.PostFilterAttributes(attributes);
attributes[typeof(DockingAttribute)] =
new DockingAttribute(DockingBehavior.Never);
}
protected override void PostFilterProperties(IDictionary properties)
{
base.PostFilterProperties(properties);
var propertiesToRemove = new string[] {
"Dock", "Anchor", "Size", "Location", "Width", "Height",
"MinimumSize", "MaximumSize", "AutoSize", "AutoSizeMode",
"Visible", "Enabled",
};
foreach (var item in propertiesToRemove)
{
if (properties.Contains(item))
properties[item] = TypeDescriptor.CreateProperty(this.Component.GetType(),
(PropertyDescriptor)properties[item],
new BrowsableAttribute(false));
}
}
}
Designer for your user control
public class MyUserControlDesigner : ParentControlDesigner
{
public override void Initialize(IComponent component)
{
base.Initialize(component);
var contentsPanel = ((MyUserControl)this.Control).ContentsPanel;
this.EnableDesignMode(contentsPanel, "ContentsPanel");
}
public override bool CanParent(Control control)
{
return false;
}
protected override void OnDragOver(DragEventArgs de)
{
de.Effect = DragDropEffects.None;
}
protected override IComponent[] CreateToolCore(ToolboxItem tool, int x,
int y, int width, int height, bool hasLocation, bool hasSize)
{
return null;
}
}

Cannot implicitly convert type 'System.Web.UI.CompiledTemplateBuilder' to custom ITemplate

When you create a ListView, there is a property on the control that allows you to specify the ID of the PlaceHolder in the LayoutTemplate that is used to hold the controls for each item.
<asp:ListView ID="lvTest" runat="server" ItemPlaceholderID="testPlaceholder">
<LayoutTemplate>
<ul>
<asp:PlaceHolder ID="testPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>Item</li>
</ItemTemplate>
</asp:ListView>
I am trying to create a custom templated server control but would like to have a property on the template itself as I expect to have several different templates. My extremely simplified, trivial example is as follows:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ControlLibrary
{
[ParseChildren(true)]
public class TestContainer : Control, INamingContainer
{
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(TestContainer))]
public TestTemplate TestTemplate { get; set; }
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
DataBind();
}
public override void DataBind()
{
base.DataBind();
CreateChildControls();
}
protected override void CreateChildControls()
{
Controls.Clear();
var phTest = new PlaceHolder();
phTest.ID = "phTest";
Controls.Add(phTest);
if (this.TestTemplate != null)
this.TestTemplate.InstantiateIn(phTest);
this.ChildControlsCreated = true;
}
}
public class TestTemplate : ITemplate
{
public string Name { get; set; }
public void InstantiateIn(Control container)
{
container.Controls.Add(new LiteralControl(this.Name));
}
}
}
However, if I add the template to my .aspx file like below I get an error saying CS0029: Cannot implicitly convert type 'System.Web.UI.CompiledTemplateBuilder' to 'ControlLibrary.TestTemplate'
<CustomControls:TestContainer ID="testContainer" runat="server">
<TestTemplate>
test
</TestTemplate>
</CustomControls:TestContainer>
Is it possible to do this or will I have to put all configurable properties on the parent container itself?
Thanks for any help you can provide!
You did everything correctly except the template property declaration. Any template must be declared as System.Web.UI.ITemplate. Just replace your template declaration with:
public ITemplate TestTemplate { get; set; }
And it should start working. For reference see How to: Create Templated ASP.NET User Controls.
To do a trick with custom attributes for template you need to add one more class inheriting from collection:
public class TestTemplateList : List<TestTemplate> { }
And change declaration of the control as following:
[ParseChildren(true, DefaultProperty = "TestTemplates")]
public class TestContainer : Control, INamingContainer
{
[PersistenceMode(PersistenceMode.InnerProperty)]
public TestTemplateList TestTemplates { get; set; }
// ... OnLoad and DataBind left intact
protected override void CreateChildControls()
{
Controls.Clear();
var phTest = new PlaceHolder();
phTest.ID = "phTest";
Controls.Add(phTest);
if (this.TestTemplates != null)
{
foreach (var testTemplate in TestTemplates)
{
((ITemplate)testTemplate).InstantiateIn(phTest);
}
}
this.ChildControlsCreated = true;
}
}
After that you should be able to declare control in both ways. You can skip specifying TestTemplates because it is declared as a DefaulProperty in ParseChildrenAttribute:
<CustomControls:TestContainer runat="server" ID="testContainer">
<CustomControls:TestTemplate Name="test">
</CustomControls:TestTemplate>
</CustomControls:TestContainer>
<%-- OR --%>
<CustomControls:TestContainer runat="server" ID="wc11">
<TestTemplates>
<CustomControls:TestTemplate Name="test">
</CustomControls:TestTemplate>
</TestTemplates>
</CustomControls:TestContainer>

ASP.Net Custom Server Control Not Firing Custom Event

I have created a custom server control. It looks great and the rendered HTML is also as it should be. I initially had it extending the ControlContainer and now it extends the WebControl (both behave the same.) It has two properties, ImageUrl and Text. Essentially it will render a generic HTML tag with an and tags within it.
My problem is that the ServerClick event that is exposed (by NamingContainer I beleive) doesn't seem to fire. If I add any of the ASP buttons (Link, Image or regular) and associate to that Click event it fires but of course I have extra rendered content. It successfully runs the javascript and does the __dopostback call. But it must not see the given control ID or something because the event never gets fired.
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace PLSO.Info.Web.UI {
[DefaultEvent("Submit")]
[DefaultProperty("Text")]
[ToolboxData("<{0}:ComboButton runat=\"server\"> </{0}:ComboButton>")]
public class ComboButton : WebControl {
private HtmlImage imageControl;
private HtmlGenericControl spanControl;
private static readonly object EventSubmitKey = new object();
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Description("The text to display on the button.")]
public string Text {
get { return ViewState["NewText"] as string; }
set { ViewState["NewText"] = value; }
}
[DefaultValue("")]
[Bindable(true)]
[Category("Appearance")]
[UrlProperty()]
[Editor("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public string ImageUrl {
get {
EnsureChildControls();
return this.imageControl.Src;
}
set {
EnsureChildControls();
this.imageControl.Src = value;
}
} // ImageUrl - Property
public override string CssClass {
get { return ViewState["CssClass"] as string; }
set { ViewState["CssClass"] = value; }
}
[Category("Action")]
[Description("Raised when the user clicks the button.")]
public event EventHandler Submit {
add { Events.AddHandler(EventSubmitKey, value); }
remove { Events.RemoveHandler(EventSubmitKey, value); }
}
protected virtual void OnSubmit(EventArgs e) {
EventHandler SubmitHandler = (EventHandler)Events[EventSubmitKey];
if (SubmitHandler != null)
SubmitHandler(this, e);
}
void ComboButton_Submit(object sender, EventArgs e) {
OnSubmit(EventArgs.Empty);
}
protected override void CreateChildControls() {
Controls.Clear();
imageControl = new HtmlImage();
imageControl.Src = this.ImageUrl;
imageControl.Alt = this.Text;
this.Controls.Add(imageControl);
spanControl = new HtmlGenericControl("span");
spanControl.InnerText = this.Text;
this.Controls.Add(spanControl);
this.Submit += new EventHandler(ComboButton_Submit);
ChildControlsCreated = true;
}
protected override void Render(HtmlTextWriter writer) {
PostBackOptions pbo = new PostBackOptions(this);
AddAttributesToRender(writer);
writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass);
writer.AddAttribute("onclick", string.Format("javascript:{0}", Page.ClientScript.GetPostBackEventReference(pbo)));
writer.RenderBeginTag(HtmlTextWriterTag.Button);
imageControl.RenderControl(writer);
spanControl.RenderControl(writer);
writer.RenderEndTag();
}
}
}
Here is my markup. I put in this control and then a regular ASP:Button. That regular button's event gets hit! Not mine.
<ucs:ComboButton ID="btnT4" runat="server" Text="Please" CssClass="PButtonCombo" ImageUrl="~/Styles/icons/edit-find.png" OnSubmit="btnT4_Submit" />
<asp:Button ID="btnT5" runat="server" Text="TEST" onclick="btnT5_Click" UseSubmitBehavior="False" />
And here is the rendered HTML:
<button id="MainContent_btnT4" class="PButtonCombo" onclick="javascript:__doPostBack('ctl00$MainContent$btnT4','')"><img src="../Styles/icons/edit-find.png" alt="Please" /><span>Please</span></button>
<input type="button" name="ctl00$MainContent$btnT5" value="TEST" onclick="javascript:__doPostBack('ctl00$MainContent$btnT5','')" id="MainContent_btnT5" />
I have to believe I am close but just missing something. Been tweaking it for hours today, PLEASE HELP!
EDIT:
Thanks to #James answer, all I did was add the following to the top of the above example. It did the trick but now fires twice. Not sure why? So that is my current question:
public class ComboButton : WebControl, IPostBackEventHandler {
public void RaisePostBackEvent(string eventArgument) {
OnClick(new EventArgs());
}
[Category("Action")]
[Description("Raised when the user clicks the button.")]
public event EventHandler Click;
protected virtual void OnClick(EventArgs e) {
if (Click != null)
Click(this, e);
}
EDIT 2 == SOLUTION
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace PLSO.Info.Web.UI {
[DefaultEvent("Submit")]
[DefaultProperty("Text")]
[ToolboxData("<{0}:ComboButton runat=\"server\"> </{0}:ComboButton>")]
public class ComboButton : Button {
private HtmlImage imageControl;
private HtmlGenericControl spanControl;
[DefaultValue("")]
[Bindable(true)]
[Category("Appearance")]
[UrlProperty()]
[Editor("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public string ImageUrl {
get {
EnsureChildControls();
return this.imageControl.Src;
}
set {
EnsureChildControls();
this.imageControl.Src = value;
}
} // ImageUrl - Property
protected override void CreateChildControls() {
Controls.Clear();
imageControl = new HtmlImage();
imageControl.Src = this.ImageUrl;
imageControl.Alt = this.Text;
this.Controls.Add(imageControl);
spanControl = new HtmlGenericControl("span");
spanControl.InnerText = this.Text;
this.Controls.Add(spanControl);
ChildControlsCreated = true;
} // CreateChildControls - Method - Override
protected override void Render(HtmlTextWriter writer) {
PostBackOptions pbo = new PostBackOptions(this);
AddAttributesToRender(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Button);
imageControl.RenderControl(writer);
spanControl.RenderControl(writer);
writer.RenderEndTag();
} // Render - Event - Override
}
}
Try implementing the IPostBackEventHandler interface:
public class ComboButton : WebControl, IPostBackEventHandler
{
public void RaisePostBackEvent(string eventArgument)
{
OnSubmit(EventArgs.Empty);
}
}
Here's an article that explains the implementation of the IPostBackEventHandler interface:
http://msdn.microsoft.com/en-us/library/system.web.ui.ipostbackeventhandler.aspx
EDIT
If your events are in some way dependent on data, you need to implement the IPostBackDataHandler interface. For example, you would use the IPostBackDataHandler interface to fire the OnTextChanged event of a TextBox:
public class ComboButton : WebControl, IPostBackDataHandler
{
public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
return true;
}
public virtual void RaisePostDataChangedEvent()
{
}
}
Here's an article that explains the implementation of the IPostBackDataHandler interface:
http://msdn.microsoft.com/en-us/library/system.web.ui.ipostbackdatahandler.aspx
You need to look into IPostBackEventHandler
If you dont implement this interface in your control ASP.net engine wont forward the events to your control.

implementing IPostbackHandler .net

I have a server control, inheriting from PlaceHolder.
Basically, all it is, is a placeholder, with the top part having a "<div class etc...", and the bottom closing it off.
So, typical usage would be
<control:control runat="server" id="phControl">
<asp:TextBox runat="server" id="txtControl">
<asp:DropDownList runat="server"id="ddlControl">
</control:control>
or something similar.
It has struck me that if I postback to the control, it loses all the items in the ddlControl (or whatever), and that implementing IPostBackHandler apparently would solve all my woes.
I had a quick glance through the documentation, but am still not really sure what I am implementing (obviously I have the method names, but I don't really get what is expected in here)
Any pointers in the right direction would be greatly appreciated.
Thanks,
Tim
Its looks like you just want a server control that can contains other controls or a "template", I have just done this using the example at: http://msdn.microsoft.com/en-us/library/ms178657.aspx
This should handle all the work done on postback.
A basic example adapted from the above link:
using System;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;
namespace Made4Print.Web.UI
{
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal), Designer(typeof(VacationHomeDesigner)), DefaultProperty("Title"), ToolboxData("<{0}:TemplateContainer runat=\"server\"> "),]
public class TemplateContainer : CompositeControl
{
private ITemplate templateValue;
private TemplateOwner ownerValue;
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public TemplateOwner Owner
{
get
{
return ownerValue;
}
}
[Browsable(false), PersistenceMode(PersistenceMode.InnerProperty), DefaultValue(typeof(ITemplate), ""), Description("Control template"), TemplateContainer(typeof(TemplateContainer))]
public virtual ITemplate Template
{
get
{
return templateValue;
}
set
{
templateValue = value;
}
}
protected override void CreateChildControls()
{
Controls.Clear();
ownerValue = new TemplateOwner();
ITemplate temp = templateValue;
if (temp == null)
{
temp = new DefaultTemplate();
}
temp.InstantiateIn(ownerValue);
this.Controls.Add(ownerValue);
}
public override void DataBind()
{
CreateChildControls();
ChildControlsCreated = true;
base.DataBind();
}
}
[ToolboxItem(false)]
public class TemplateOwner : WebControl
{
}
#region DefaultTemplate
sealed class DefaultTemplate : ITemplate
{
void ITemplate.InstantiateIn(Control owner)
{
// Create Controls Here
//Label title = new Label();
//title.DataBinding += new EventHandler(title_DataBinding);
//owner.Controls.Add(title);
}
//void title_DataBinding(object sender, EventArgs e)
//{
// Label source = (Label)sender;
// TemplateContainer container = (TemplateContainer)(source.NamingContainer);
// source.Text = container.Title;
//}
}
#endregion
public class VacationHomeDesigner : ControlDesigner
{
public override void Initialize(IComponent Component)
{
base.Initialize(Component);
SetViewFlags(ViewFlags.TemplateEditing, true);
}
public override string GetDesignTimeHtml()
{
return "<span>[Template Container Control]</span>";
}
public override TemplateGroupCollection TemplateGroups
{
get
{
TemplateGroupCollection collection = new TemplateGroupCollection();
TemplateGroup group;
TemplateDefinition template;
TemplateContainer control;
control = (TemplateContainer)Component;
group = new TemplateGroup("Item");
template = new TemplateDefinition(this, "Template", control, "Template", true);
group.AddTemplateDefinition(template);
collection.Add(group);
return collection;
}
}
}
}

Categories