Brunov's blog

Sergey Vyacheslavovich Brunov's blog

WPF: Specify your DataContext type

2012-02-20 15:21:21 Moscow time

Using WPF with MVVM approach it is hard to keep in memory all types of the ViewModels you're working with for databinding.
There is a quite useful feature which allows you to specify type of DataContext explicitly for each View (UI element).

Assume you have BookViewModel class with Author, Title properties. Also, you have a StackPanel in your XAML to display information about some book.

  1. Add the XML-namespaces to your root View: xmlns:d="http://schemas.microsoft.com/expression/blend/2008", xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006".

  2. Add the attribute mc:Ignorable="d" to your root View.

  3. Add the following StackPanel:

    <StackPanel Orientation="Vertical" d:DataContext="{d:DesignInstance vm:BookViewModel}">
        <TextBlock Text="{Binding Path=Author, Mode=OneWay}" />
        <TextBlock Text="{Binding Path=Title, Mode=OneWay}" />
    </StackPanel>
    

Also, JetBrains ReSharper will show you the warning if DataContext type is unknown:

Cannot resolve symbol '...' due to unknown DataContext.

But when the DataContext type is specified and you try using the property which does not exist in the ViewModel, ReSharper will warn you:

Cannot resolve symbol '...'.

This makes data binding implementation less error-prone.

Additional information: Walkthrough: Using a DesignInstance to Bind to Data in the Designer.

Tags: databinding datacontext mvvm wpf