Today I’d like to share a trick I used while developing my first Windows Store application. I’m very new to this technology and it’s my first article about it, so I hope I won’t make a fool of myself…

It’s often useful to be notified when the value of a dependency property changes; many controls expose events for that purpose, but it’s not always the case. For instance, recently I was trying to detect when the Content property of a ContentControl changed. In WPF, I would have used the DependencyPropertyDescriptor class, but it’s not available in WinRT.

Fortunately, there is a mechanism which is available on all XAML platforms, and can solve this problem: binding. So, the solution is just to create a class with a dummy property that is bound to the property we want to watch, and call a handler when the value of the dummy property changes. To make it cleaner and hide the actual implementation, I wrapped it as an extension method that returns an IDisposable:

The DataContext property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don’t need to set it again on each element you want to bind. However, in some cases the DataContext is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements…

Let’s illustrate with a simple example: we want to display a list of products in a DataGrid. In the grid, we want to be able to show or hide the Price column, based on the value of a ShowPrice property exposed by the ViewModel. The obvious approach is to bind the Visibility of the column to the ShowPrice property:

The message is rather cryptic, but the meaning is actually quite simple: WPF doesn’t know which FrameworkElement to use to get the DataContext, because the column doesn’t belong to the visual or logical tree of the DataGrid.

We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to the DataGrid itself:

But none of these workarounds seems to work, we always get the same result…

At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern… But I’m not going to give up so soon, at least not while there are other options to consider

The solution to our problem is actually quite simple, and takes advantage of the Freezable class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that Freezable objects can inherit the DataContext even when they’re not in the visual or logical tree. I don’t know the exact mechanism that enables this behavior, but we’re going to take advantage of it to make our binding work…

The idea is to create a class (I called it BindingProxy for reasons that should become obvious very soon) that inherits Freezable and declares a Data dependency property:

Visual Studio 2010 beta 2 has been released last week, and it brings to WPF a long awaited feature : support for bindings in InputBindings.

As a reminder, the issue in previous releases was that the Command property of the InputBinding class wasn’t a DependencyProperty, so it wasn’t possible to bind it. Furthermore, InputBindings didn’t inherit the parent DataContext, which made it difficult to provide alternative implementations…

Until now, in order to bind the Command of a KeyBinding or MouseBinding to a property of the DataContext, we had to resort to clumsy workarounds… I had eventually came up with an acceptable solution, described in this post, but I wasn’t really satisfied with it (it used reflection on private members, and had annoying limitations).

More recently, I found a better solution in the MVVM toolkit : a CommandReference class, inherited from Freezable, allows to put a reference to a ViewModel command in the page or control resources, so that it can be used later with StaticResource. It’s much cleaner than my previous solution, but still not very straightforward…

WPF 4.0 solves that problem once and for all : the InputBinding class now inherits from Freezable, which allows it to inherit the DataContext, and the Command, CommandParameter and CommandTarget properties are now dependency properties. So, at last, we can forget about the clumsy workarounds described above, and go straight to the point :

This new feature should make it much easier to develop MVVM applications !

Help 3

Other than that, I would like to say a few words about the new offline help system that comes with Visual Studio 2010, called “Help 3″. It’s quite a big change compared to previous versions… First, it’s not a standalone application anymore, but a locally hosted web application, so you can access the documentation with your favorite web browser. On the whole, it’s better than the previous system… much faster and more responsive than the old Document Explorer included in previous Visual Studio releases.

However, the new system misses the feature that was the most useful to me : the index ! Now there’s only the hierarchical view, and a search textbox. IMHO, the index was the most convenient way of looking up something in the doc, it made it very easy to access a class or member directly, even without knowing its namespace… why on earth did they remove it ? Worse still : the search results don’t show the namespace, only the class or member name. For instance, if you search “button class”, in the results there is no way to see the difference between System.Windows.Forms.Button, System.Windows.Controls.Button and System.Web.UI.WebControls ! You have to click each link and see where it leads… In Document Explorer, the Index Results pane showed this information clearly.

So, eventually I have mixed feelings about this new help system, because I will have to change the way I use the documentation. But except for this annoying detail, I must concede that it’s objectively a big improvement over the old system…

As you may have noticed, it is not possible to modify the contents of an ObservableCollection on a separate thread if a view is bound to this collection : the CollectionView raises a NotSupportedException :

This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread

To illustrate this, let’s take a simple example : a ListBox bound to a collection of strings in the ViewModel :

If we add items to this collection out of the main thread, we get the exception mentioned above. A possible solution would be to create a new collection, and assign it to the Strings property when it is filled, but in this case the UI won’t reflect progress : all items will appear in the ListBox at the same time after the collection is filled, instead of appearing as they are added to the collection. It can be annoying in some cases : for instance, if the ListBox is used to display search results, the user expects to see the results as they are found, like in Windows Search.

A simple way to achieve the desired behavior is to inherit ObservableCollection and override OnCollectionChanged and OnPropertyChanged so that the events are raised on the main thread (actually, the thread that created the collection). The AsyncOperation class is perfectly suited for this need : it allows to “post” a method call on the thread that created it. It is used, for instance, in the BackgroundWorker component, and in many asynchronous methods in the framework (PictureBox.LoadAsync, WebClient.DownloadAsync, etc…).

So, here’s the code of an AsyncObservableCollection class, that can be modified from any thread, and still notify the UI when it is modified :

The ListBox can now reflect in real-time the changes made on the collection.

Enjoy

Update : I just found a bug in my implementation : in some cases, using Post to raise the event when the collection is modified from the main thread can cause unpredictable behavior. In that case, the event should of course be raised directly on the main thread, after checking that the current SynchronizationContext is the one in which the collection was created. This also made me realize that the AsyncOperation actually doesn’t bring any benefit : we can use the SynchronizationContext directly instead. So here’s the new implementation :

Update: changed the code to use Send instead of Post. Using Post caused the event to be raised asynchronously on the UI thread, which could cause a race condition if the collection was modified again before the previous event was handled.

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. However, if there are many settings, it can be a real hassle for the developper to handle them… even with the help of the Settings class generated by Visual Studio, there is still quite a lot of code to write to apply these settings to the user interface, then update them according to user modifications.

In Windows Forms, it was possible to define bindings between control properties and application settings, but it wasn’t very intuitive, and wasn’t very widely used (I’m not so sure about that, but I actually never saw it used by anyone…).

With WPF, we can do something similar in a much more elegant way… although it’s not “officially” documented, it is possible to create bindings to application settings in XAML. For instance, to persist the window size and position in application settings, many blogs suggest this approach :

(In that example, Height, Width, Top and Left are application settings)

This code does work, but honestly, do you feel like writing this for every setting of the application ? It’s too verbose, not intuitive, and makes the code harder to read…

Of course, I’m not saying this idea is bad… but it’s very easy to improve it, by creating our own « markup extension ». In this post I’m going to explain how to write a class that inherits Binding, and allows to bind easily to application settings.

« Markup extension » are objects that can be used in XAML to retrieve values. They are used all the time in WPF : for instance, Binding, StaticResource and DynamicResource are markup extensions.

It’s quite easy to define your own markup extension, by creating a class that inherits the abstract MarkupExtension class, and implements the ProvideValue method. In our case, most of what we need is already implemented in the Binding class (which indirectly inherits MarkupExtension). So we’re just going to inherit Binding, and initialize the necessary properties in order to bind to application settings :

Note the « Extension » suffix at the end of the class name : by convention, most markup extensions have this suffix (Binding is an exception…). It can be omitted when using the class in XAML (similarly to attributes, for which the « Attribute » suffix can be omitted).

In that class, we defined two constructors, matching those of the Binding class. We don’t need to redefine the ProvideValue method, because the one implemented in the Binding class suits us perfectly (and anyway it is marked as sealed, so we couldn’t override it even if we wanted to…). The part that actually makes the code work is the Initialize method. It initializes the Source property, so that the Path of the binding maps to the specified setting, and sets Mode to TwoWay so that application settings are automatically updated from the UI. The point of doing this is that we don’t have to set these properties every time we bind to a setting…

To illustrate the usage of this markup extension, let’s go back to the previous example, and replace the Bindings with the SettingBinding extension :