In my previous post I constructed a (very) simple WebPart composite control which displays some text. Next we'll need to be able to edit this text using the WebPart framework. Now there is already a component which is able to edit the properties of any WebPart, but wouldn't it be cooler to provide our own custom UI? Of course it would, so let's make it so!
In order to provide our own UI, we'll need to build an EditorPart. Simple enough, the structure is very much like the WebPart we'll be editing. First derive a class from EditorPart:
public class TextEditorWebPart : EditorPart
{
}
First we'll use CreateChildControls to build up our editor UI. A simple TextBox will do just fine:
TextBox
_textField;
protected override void CreateChildControls()
{
_textField = new TextBox();
_textField.ID = "editField";
Controls.Add(_textField);
ChildControlsCreated = true;
}
Now in order to communicate with the WebPart we're editing, two methods need to be overriden, ApplyChanges and SyncChanges. The first is used to send the new value to the WebPart, the second retrieves the value from the WebPart into the editor. The WebPart which is being edited by the EditorPart, is available from the WebPartToEdit property. Also note the use of EnsureChildControls to make sure the TextBox is created before calling it.
public override bool ApplyChanges()
{
EnsureChildControls();
TextWebPart part = (TextWebPart)WebPartToEdit;
part.Text = _textField.Text;
return true;
}
public override void SyncChanges()
{
EnsureChildControls();
TextWebPart part = (TextWebPart)WebPartToEdit;
_textField.Text = part.Text;
}
There is still one final thing to perform, connect the WebPart and the EditorPart. This is done in the code I provided in my previous post. The TextWebPart needs to be expanded with two overrides:
public override object WebBrowsableObject
{
get { return this; }
}
public override EditorPartCollection CreateEditorParts()
{
return new EditorPartCollection(
new EditorPart[] { new TextEditorWebPart() });
}
The first override is used by the EditorPart to retrieve a reference to the control being edited. The second override creates the custom EditorPart for display when the WebPartManager is in the 'edit' displaymode.
That's all there is to creating a custom editor for your WebPart. Quite nice, my only problem is that the editor UI is not inferred over the WebPart itself, but shown in a seperate EditorZone. I think I'll try and do something about that later on.
Posted
25-07-2005 8:58
by
Anonymous