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.
- 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"
. - Add the attribute
mc:Ignorable="d"
to your root View. - 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.
Thanks for your advices 🙂
Thanks! Now I can clean up a bunch of Resharper warnings in my XAML.
Instead of “#8243;”, there should be an end quote.
Thank you for pointing out! Have just updated the post.
what about vm namespace? how to define it?
The details can be found here: XAML Namespaces and Namespace Mapping for WPF XAML, MSDN. For example:
or
and in this case: