A recent post by Josh Twist shows how to support mingling code in XAML for WPF devs. There have been several examples of putting code into XAML over the years, and they always raise the discussion of whether or not it is a good practice. I am usually against having code in XAML because it makes it difficult to debug and maintain, but to each his/her own. Regardless, that post got me thinking…
For a while now I’ve wondered how one might go about making it so that the little bits of code in the XAML might somehow be transplanted into the highly testable, debuggable, lovable world of the ViewModel. Sure, you could put this type of logic into value converters, but writing a value converter that is only used once seems like a lot of extra work for little benefit.
Just for kicks, I decided to implement a class that would allow you to specify a method on your ViewModel object that contains the code that would otherwise be placed into a value converter, or in XAML. The result is a markup extension I ever so lazily named BindingEx. Here’s a simple usage:
Notice the last bit where the ConvertMethod property is set to AdjustTextWidth. This is how you specify which method on the element’s VM should be invoked when the window’s width changes. Here’s the VM class:
The TextViewModel object halves the window’s ActualWidth, and that value ends up being the width of the TextBlock.
I’m not sure that anyone should ever use this technique in a real application. It’s probably a very stupid idea altogether, so I want to avoid any bad karma by stressing the point here: USE AT YOUR OWN RISK!!
If you want to check out how I implemented BindingEx, click here to download the source code. Be sure to change the file extension from .DOC to .ZIP and then decompress it.