User login |
WPF: Embedding DLR Scripts in XAML (Python, Ruby) - Part 2, A Simple DLR Markup ExtensionA Visual Studio 2008 Solution with the complete code listing for this series is attached to the final part. This article demonstrates how to embed DLR scripts in XAML using a custom MarkupExtension. The scripting language can be any language supported by the DLR, such as Python or Ruby. The first article in this series demonstrated how to host the DLR and presented some utility methods that make executing scripts simple. Here we build upon this to create a simple MarkupExtension that evaluates a DLR expression.
The purpose of a MarkupExtension is to provide a value during XAML parsing. The MarkupExtension is then substituted with this value and parsing continues. A MarkupExtension that evaluates a DLR Expression is shown below.
While very simple, there are two problems with the class as written:
The full listing for the class with these enhancements is as follows:
Now we can use the ScriptExtension in our XAML files. The following will display the value "11" in a TextBlock, where "11" was calculated by evaluating the Python expression "5+6":
The MarkupExtension notation (that inside the braces, "{...}") limits what we can put in the expression. For example, we can not use quotes, so some expressions in some languages simply can't be written. To overcome this we use Property Element notation. The following will display the string "Hello World" in a TextBlock, the string was calculated by evaluating the Python expression "Hello " + "World":
As discussed in Part 1 of this series, it is often necessary for the expression to be evaluated in the context of some other script. This can be done by setting the Script property of the ScriptExtension. This script will inevitably be a multiline string and we will hit problems with the preservation of whitespace during XAML parsing. I have written an article on this previously and use that technique here. The following example defines a recursive function to calculate a factorial in the Python script. The Text property of the TextBlock will be set to 120, which is the factorial of 5:
This DLR Script MarkupExtension was very simple to write, yet allows the programmer so much freedom when setting object property values. The next articles in this series will demonstrate how to use DLR scripting in other parts of WFP such as ValueConverters, Commands and Event Handlers. |