Recently I had the requirement in the title: we built a custom webpart based on the built-in XsltListViewWebPart. Microsoft wisely follows the best-practice pattern composition over inheritance, making the said webpart sealed (yes, it was sarcasm) so we generate one on the fly and we needed to pass some parameters to these generated XsltListViewWebParts and be able to access and work with these parameters in the XSL template.
The solution isn’t particularly hard but it took me a lot of googling, so I thought it might worth sharing it here. It has the following steps:
- Add your custom parameter to the XsltListViewWebPart’s ParameterBindings property.
- In the XSL file create an XSL parameter with the name of your custom parameter.
- Select the value of the XSL parameter in the XSL file to be able to work with it.
The first part was easy, especially with the help of Stefan Stanev’s post which covers the ParameterBindings property in great detail. There’s only one gotcha here: the type of the ParameterBindings property is string. I wasn’t become too depressed by this fact, simply concatenating your custom value will do the job:
myWebPart.ParameterBindings += @”<ParameterBinding Name=””myParameter”” DefaultValue=””Hello!”” />”;
The second part is easy too: just add an XSL parameter to your XSL file, like:
<xsl:param name=”myParameter” />
After you’ve done this, you’ll be able to access the value of the parameter (in our case, “Hello!”) using the following XSL query in your XSL file:
<xsl:value-of select=”$myParameter” />
Well, that’s all. Hope it helps someone out.