WPF: Specify your DataContext type

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.

6 thoughts on “WPF: Specify your DataContext type

    1. Sergey Brunov Post author

      The details can be found here: XAML Namespaces and Namespace Mapping for WPF XAML, MSDN. For example:

      xmlns:vm="clr-namespace:TheApplication.ViewModels;assembly=TheApplication"
      

      or

      assembly can be omitted if the clr-namespace referenced is being defined within the same assembly as the application code that is referencing the custom classes. Or, an equivalent syntax for this case is to specify assembly=, with no string token following the equals sign.
      XAML Namespaces and Namespace Mapping for WPF XAML, MSDN

      and in this case:

      xmlns:vm="clr-namespace:TheApplication.ViewModels"
      
      Reply

Leave a Reply (Markdown is enabled)

Your email address will not be published. Required fields are marked *