Thursday, 16 June 2011

Resharper 6 XAML Tip: Intellisense for your Databindings

Anybody who has installed the Resharper 6 Beta (and that should be all of you – it’s awesome, and no major problems that I can see) will find in it a feature I’ve been wanting ever since WPF was first released: intellisense for databindings.

Mark up your Xaml so that Resharper knows the type of your DataContext and it will tell you what properties you can bind to, and warn you if it doesn’t recognize what you’ve typed. I’m always switching back and forth between my Views and ViewModels to make sure I get my property names right, so this will be a real time-saver.

There are lots of places where Resharper can already deduce the type of the DataContext – within DataTemplates where you’ve specified a DataType, for example. In other cases, there's just one thing you have to do to enable this awesome feature.

At the root of your file, you need to add the d:DataContext attribute and set it to the type of you Datacontext. Here’s an example:

<UserControl x:Class="MyApp.Views.MyView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:ViewModels="clr-namespace:MyApp.ViewModels"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance ViewModels:MyViewModel, IsDesignTimeCreatable=False}">

Now if you press Ctrl-Space within a binding element, you’ll get lovely intellisense:

image