SiteMapPath nodeTemplate custom definition
Reference: http://www.jordomedia.com/RSS/l_op=viewrss/lid=36720.html
This is a bit of a follow on to my last post. At the end, I made an update about how to make use of custom TreeNodes in a databound scenario. I did that example with the CSSTreeNode instead of the TemplatedTreeNode because the custom property in the templated case was an ITemplate. Trying to assign a value to that property is a great deal more difficult than a string property. And that got me thinking...
Lets start with something that seems pretty simple:
<asp:SiteMapPath ID="SiteMapPath1" runat="server">
<NodeTemplate>
<%# Eval("title") %>
</NodeTemplate>
</asp:SiteMapPath>
What if you wanted to add this control to the page dynamically? How would you write it in code? Well, adding the SiteMapPath to the page is pretty simple. But the NodeTemplate isn't so simple. What actually happens in that case is a mechanism in the framework creates a new object on the fly that implements the ITemplate interface and generates some code to populate the template. In order to do this manually, the developer would have to create his/her own ITemplate object and databinding code. Here's a simplified version of what that code might look like:
public class MyTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
Label l1 = new Label();
container.Controls.Add(l1);
l1.DataBinding += new EventHandler(l1_DataBinding);
}
void l1_DataBinding(object sender, EventArgs e)
{
Label l1 = sender as Label;
SiteMapNodeItem container = l1.BindingContainer as SiteMapNodeItem;
l1.Text = container.SiteMapNode.Title;
}
}









Keep in mind, this code is for a single eval statement. If you wanted to add several controls, some styles, maybe another template or two (perhaps 20 lines of markup), this could quickly become 100+ lines of code for this single control. This is especially unfortunate because this is work that the parser can do reliably and quickly.
So the question is, how can I get the parser to parse the template markup for me and yet present me with a reference to the ITemplate object instead of consuming it?