views:

76

answers:

1

Is there a way to examine the contents of a DataTemplate in code? I want to list out the controls in a datatemplate, looking for a specific type.

Thanks!

A: 

In my opinion, the best (and recommended) way is to use XamlWriter/XamlReader with LINQ to XML. For example:

string templateXaml = XamlWriter.Save(template);

XElement xData = XElement.Parse(templateXaml);

XElement xpanel = xData.XPathSelectElements("//*[@IsItemsHost]").FirstOrDefault();

This would find the xaml element with an existing IsItemsHost attribute.

Then, if you would like to examine it as a dependency object programmatically, transform it like this:

Panel panel = (Panel) XamlReader.Parse(xpanel.ToString());

//example, discover which panel Type it actually is
Type panelType = panel.GetType();

EDIT

Also, to answer your question directly, additionally you would write code like this:

IEnumerable<XElement> typedElements = xData.XPathSelectElements("//SpecificType");

foreach(XElement el in typedElements)
{
    DependencyObject dObj = (DependencyObject) XamlReader.Parse(el.ToString());

    //do something with dObj
}
kek444