/ MVVM

Setting 'd:DataContext" Attribute on Every View

In MVVM applications it is useful to specify the d:DataContext attribute on every view even if you don't work in Expression Blend and don't use design-time data.

<UserControl x:Class="loc:MyView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:loc="clr-namespace:…"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance loc:MyViewModel}">
       …
</UserControl>

Besides its primary purpose (providing design-time data context) it is also useful thing to have on every view for the following reasons:

  • It lets developers know what view model is used with this view (what the data context is) and allows them quickly navigate to it when needed;
  • It tells ReSharper about the data context, so it can help you with IntelliSense when you create bindings (type {Binding and hit ctrl+alt+space and ReSharper will suggest you the list of properties of your view model). Also ReSharper will highlight errors if you misspell the property name.

As you see, with this simple attribute you kill three birds in one stone. I already developed a habit to specify this attribute right after I create a new view and feel a bit lost when I open an old one that doesn't have it.

Hope you'll find this tip useful.

Pavlo Glazkov

Pavlo Glazkov

Programmer. Full stack, with a focus on UI. JavaScript/TypeScript, Angular, Node.js, .NET

Read More