The first thing that is needed when developing a templated control designer is the templated control itself. For use in this paper a simple templated control has been developed, the DuoView. It looks and feels like the new LoginView control found in the ASP.NET 2.0 toolkit, but the mechanism used to switch the displayed template differs. Unlike the LoginView, which activates a template based on the authentication state of a user, the DuoView gives the developer the ability to choose the active template.
The control is made up of two templates. The template to display is indicated using the DisplayMode enumeration and the ActiveDisplayMode property, which can be set at runtime. The value for the property is stored using control state which allows the state to be remembered during postbacks, even when the use of ViewState is turned off for the control. The code in the following figure displays the switching logic.
I will not go in to deep on how to develop a templated control, you can read about this in various papers on MSDN for instance.
public enum DisplayMode { FirstTemplate = 0, SecondTemplate = 1 };public DisplayMode ActiveDisplayMode
{ get { return _activeDisplayMode; } set
{ if (!Enum.IsDefined(typeof(DisplayMode), value))
{ throw new ArgumentOutOfRangeException("value"); }
if (value != _activeDisplayMode)
{ OnViewChanging(EventArgs.Empty);
_activeDisplayMode = value;
ChildControlsCreated = false;
ClearChildViewState();
OnViewChanged(EventArgs.Empty);
}
}
}
Figure 1. Template switching logic
When changing the active template it will have to be re-instantiated and added to the control collection of the DuoView. The actual instantiation of the template isn’t performed by this property. The template is instantiated on demand when accessing the Controls collection for instance. The ChildControlsCreated flag is used to indicate that instantiation is required. The ActiveDisplayMode property just toggles the flag and uses a simple event mechanism to notify when the active template changes.
The active template is instantiated using an override of the CreateChildControls method. When called, the template indicated by ActiveDisplayMode is instantiated, and the resulting control is added to the Controls collection of the DuoView. Access to the right template is provided using the ActiveTemplate property.
protected virtual ITemplate ActiveTemplate
{ get { return _templates[(int)_activeDisplayMode]; }}
protected override void CreateChildControls()
{ Controls.Clear();
ITemplate template = ActiveTemplate;
if (template != null)
{ Control control = new Control();
template.InstantiateIn(control);
Controls.Add(control);
}
ChildControlsCreated = true;
}
Figure 2. Instantiating the right template
That’s it for the DuoView control. All the rest is the usual boilerplate code for a templated control. The interesting part is ahead, implementing the designer.