Using IronPython in WPF to evaluate expressions

IronPython makes a ridiculously good expression evaluator, and for some reason it seems to get used a lot for adding dynamic features to WPF. For example see Using IronPython for Converters in Silverlight and Binding Dynamic Types with WPF.

This Code Project article, by Sacha Barber, uses IronPython with WPF to evaluate mathematical expressions from C#.
I have just read a little book on IronPython and thought it a pretty cool language. What I especially liked was the fact that it can be hosted in .NET as a script. This gave me an idea, wouldn't it be cool if we could use IronPython as a script to evaluate mathematical expressions for us and return a value.

Think javascripts eval function, which is missing from C# (at least it is right now, it may be part of C# 4.0 who knows). So with this thought in mind I whipped up a small proof of concept and was actually very pleased with the results, so much so I have turned it into this article.

You may be asking why would I possibly want to use a mathematical expression in WPF. Well here is one common usage, you have a UI element that you want to be as wide as its container - some magic number, this is something you could do with a standard IValueConverter, but what if you want another expression, you would need another IValueConverter implementation. That ain't cool.

So lets have a look at what I came up with.

I have come up with 2 options a MarkupExtension and a IMultiValueConverter implementation.

Comments

Popular posts from this blog

Extending Abobe Flash Player and AIR with Python and Ruby

IronPython Tools for Visual Studio CTP3

Further Adventures of the Debugger