I'm currently writing the chapter about control templates in our WPF book, and I wanted to include a list of all of the named parts that are hidden away in the dark recesses of the various controls. Before I even started googling, I had an idea that I thought I'd share.
For those of you not yet familiar with control templates, WPF allows you to redefine the visual appearance of controls. The problem is that some of the controls have special named parts, that is, there are visual elements with specific names that the code expects to be there. Luckily, there is the TemplatePartAttribute that's meant to decorate controls with named parts. If you look at the documentation for a given control, the attributes are listed and you'll know what named elements a new template requires.
Given an assembly though, it's quite easy to identify the controls programmatically. Here's some C# that does just that:
using System;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
namespace TemplatesParts
{
class Program
{
static void Main()
{
var assembly = Assembly.GetAssembly(typeof (Control));
var attributeType = typeof (TemplatePartAttribute);
var controls = from c in assembly.GetTypes()
where c.GetCustomAttributes(attributeType, false).Length > 0
orderby c.Name
select new {c.Name,Parts=c.GetCustomAttributes(attributeType, false)};
foreach (var control in controls)
{
Console.WriteLine(control.Name);
foreach (var part in control.Parts)
{
Console.WriteLine( " " + ((TemplatePartAttribute)part).Name);
}
}
Console.ReadLine();
}
}
}
Now, if I can just look this up in the documentation, why bother with this code? It was fun, what can I say?