Home > IronPython, WPF > Getting WPF Control Template in IronPython

Getting WPF Control Template in IronPython

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())
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: