Create SharePoint (2010) ToolPart usable for more than one WebPart

986 Views Asked by At

I am using the basic instructions (here) for creating a property driven by a custom ToolPart.

All is good, except for the part where, in order to access the webpart property within the ApplyChanges method I must cast the "this.ParentToolPane.SelectedWebPart" back to a concrete "SimpleWebPart" class.

public override void ApplyChanges()
{
    SimpleWebPart wp1 = (SimpleWebPart)this.ParentToolPane.SelectedWebPart;

// Send the custom text to the Web Part.
    wp1.Text = Page.Request.Form[inputname];
}

Doing this means that I must pair each toolpart with a specific webpart. Is there a better way? I cannot create an interface as there is no way of specifying a property in one.

I ineptly tried an passing an event/eventhandler during toolpart creation, but that did not update the webpart property when called.

I could create a base class for all the webparts that have a public "Text" property, but that is fugly.

I could also get desperate and crack open the this.ParentToolPane.SelectedWebPart reference with Reflection and call any properties named "Text" that way.

Either way, I am staring down the barrel of a fair bit of faffing around only to find out each option is a dead end.

Has anyone done this and can recommend the correct method for creating a reusable toolpart?

1

There are 1 best solutions below

0
On

I have used an interface instead of a specific instance of a webpart.

private class IMyProperty
{
    void SetMyProperty(string value);
}

public override void ApplyChanges()
{
    IMyProperty wp1 = (IMyProperty)this.ParentToolPane.SelectedWebPart;

    // Send the custom text to the Web Part.
    wp1.SetMyProperty(Page.Request.Form[inputname]);
}

But this does not give a compile time warning that the toolpart requires the parent webpart to implement the IMyProperty interface.

The simple solution to that is to add a property of the IMyProperty interface in the toolpart constructor and call this reference instead of the this.ParentToolPane.SelectedWebPart property.

public ToolPart1(IContentUrl webPart)
{
    // Set default properties              
    this.Init += new EventHandler(ToolPart1_Init);
    parentWebPart = webPart;
}

public override void ApplyChanges()
{
    // Send the custom text to the Web Part.
    parentWebPart.SetMyProperty(Page.Request.Form[inputname]);
}

public override ToolPart[] GetToolParts()
{
    // This is the custom ToolPart.
    toolparts[2] = new ToolPart1(this);
    return toolparts;
}

This works fine, but I cannot get over the feeling that there is something nasty in the underlying SharePoint code that may trip me up later.