Archive

Posts Tagged ‘controltemplate’

Getting WPF Control Template in IronPython

October 14, 2009 Leave a comment

I always find myself needing a control template so I can customize one of the WPF controls. I used to fire up Expression Blend to get it, and then realized I could write a little IronPython code to do it. Paste this code into the IronPython 2.0 or 2.6 console to see it work!

import clr
clr.AddReference("System.Xml")
clr.AddReference("PresentationFramework")
from System.Windows import Window
from System.Windows.Controls import *
from System.Windows.Markup import XamlWriter
from System.Xml import XmlWriter, XmlWriterSettings
from System.Text import StringBuilder

# Need to render the control on screen so it will have a Control Template
def getControlTemplate(ctl):
   "Gets the control template for a WPF control"
   window = Window()
   window.Content = ctl
   window.Show() 
   window.Close()
   return ctl.Template

settings = XmlWriterSettings()
settings.Indent = True
settings.IndentChars = "   "
sb = StringBuilder()
writer = XmlWriter.Create(sb,settings)
### replace Button() with an instance of whatever control you want. ###
XamlWriter.Save(getControlTemplate(Button()), writer)
print (sb.ToString())