Replacing Property Rendering Using Adapters
My colleague, Steve, wrote an excellent post on how the new property architecture in CMS 5 allows us take control of the property rendering. This post is a followup, illustrating the same example as Steve did, but this time using Controls Adapters.
EPiServer has a base class called EPiServer.Web.PropertyControls.Adapters.PropertyDataControlAdapter to facilitate implementation of a custom control adapter for a property. PropertyDataControlAdapter implements many of the properties and methods that exist on PropertyDataControl and the default behavior is to redirect the method back to the current PropertyDataControl. This makes it a simple task to implement the specific methods that you want to change the behavior for. Add the following class to your project:
public class MyPropertyStringAdapter :
EPiServer.Web.PropertyControls.Adapters.
PropertyDataControlAdapter
{
public override void CreateDefaultControls()
{
bool needContainer = false;
if (this.PropertyDataControl.AttributeSourceControl.
ControlStyle.IsEmpty == false)
needContainer = true;
ITextControl target;
if (needContainer == true)
{
// Default is a Label control, which will
// render a span tag around the content.
target = new Label();
target.Text = this.ToWebString();
// The label should get the styles, the
// Literal will not.
this.PropertyDataControl.
CopyWebAttributes((WebControl)target);
}
else
{
// The Literal will only render the text
target = new Literal();
target.Text = this.ToWebString();
}
this.PropertyDataControl.Controls.Add((Control)target);
}
}
I'm using the same code that Steve did in his sample, but with one adjustment. Since we're overriding the PropertyDataControl behavior from inside the ProperertyDataControlAdapter class, we need to use the PropertyDataControl property to access the current Control.
Now comes the cool part:
To let ASP.NET (and EPiServer) know that I wish to use my custom ControlAdapter class, I add the following line to the project's .browser file (located in the App_Browsers folder):
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="EPiServer.Web.PropertyControls.
PropertyStringControl"
adapterType="EPiServer.Demo.MyPropertyStringAdapter" />
</controlAdapters>
</browser>
</browsers>
Note that I am applying this to all browsers (ref. "Deafult"), but you can write adapters for specific browsers and wire them up in the same way, i. e you can change the behavior of a property depending on the web browser of the current request.
02 March 2008