It’s been a while since I last wrote about markup extensions… The release of Visual Studio 11 Developer Preview, which introduces a number of new features to WPF, just gave me a reason to play with them again. The feature I’m going to discuss here is perhaps not the most impressive, but it fills in a gap of the previous versions: the support of markup extensions for events.
Until now, it was possible to use a markup extension in XAML to assign a value to a property, but we couldn’t do the same to subscribe to an event.
Note : This post follows the one about a a markup extension that can update its target, and reuses the same code.
You may have noticed that using a custom markup extension in a template sometimes lead to unexpected results… In this post I’ll explain what the problem is, and how to create a markup extensions that behaves correctly in a template.
The problem Let’s take the example from the previous post : a markup extension which gives the state of network connectivity, and updates its target when the network is connected or disconnected :
If you have read my previous posts on the topic, you know I’m a big fan of custom markup extensions… However, they have a limitation that can be quite annoying : they are only evaluated once. Yet it would be useful to be able to evaluate them again to update the target property, like a binding… It could be useful in various cases, for instance :
if the value of the markup extension can change in response to an event
If you develop WPF applications according to the Model-View-ViewModel pattern, you may have faced this issue : in XAML, how to bind a key or mouse gesture to a ViewModel command ? The obvious and intuitive approach would be this one :
<UserControl.InputBindings> <KeyBinding Modifiers="Control" Key="E" Command="{Binding EditCommand}"/> </UserControl.InputBindings> Unfortunately, this code doesn’t work, for two reasons :
The Command property is not a dependency property, so you cannot assign it through binding InputBindings are not part of the logical or visual tree of the control, so they don’t inherit the DataContext A solution would be to create the InputBindings in the code-behind, but in the MVVM pattern we usually prefer to avoid this… I spent a long time looking for alternative solutions to do this in XAML, but most of them are quite complex and unintuitive.
Hi, this is my first post on this blog, I hope you will enjoy it ;-). If you want to know a few things about me, please check out this page.
The end-user of any application expects that his preferences (window size, state of this or that option…) are saved to be restored at the next run : that’s why .NET 2.0 introduced application settings as a unified way to persist these settings.