0
votes

I read this article http://msdn.microsoft.com/en-us/magazine/hh852595.aspx to try to understand data binding in WPF. But it only takes about how to bind data context in code.

ContentPanel.DataContext = _currentPerson;

I have this Item page xaml. I don't understand how does DataContext is being setup. What is the difference between DataContext attribute and d:DataContext attribute?

<Page
    x:Class="Myapp.ItemPage"
 DataContext="{Binding DefaultViewModel.Item, RelativeSource={RelativeSource Self}}"
    d:DataContext="{Binding Groups[0].Items[0], Source={d:DesignData Source=../OneList.Shared/DataModel/SampleData.json, Type=data:SampleDataSource}}"
 >
...
</Page>
2
d:DataContext is for Design-time and DataContext is for Run-timeSomeCode.NET

2 Answers

1
votes

Page DataContext is set at this line:

DataContext="{Binding DefaultViewModel.Item, RelativeSource={RelativeSource Self}}"
  • ItemPage must have property DefaultViewModel. So, you are binding DataContext to Item property of DefaultViewModel instance.

  • By RelativeSource Self, you asked binding engine to look for property DefaultViewModel within page.

Moreover, DataContext is inheritable Dependency Property so child elements will automatically inherit DataContext from it's Parent Page. And to resolve any bindings, WPF binding engine looks for property in it's DataContext unless you explicitly asked it to look somewhere else by using RelativeSource markup extension.


d:DataContext is used for design mode only whereas DataContext is used to resolve bindings at runtime.

With d:DataContext you provide dummy DataContext which will be used by Designer View to give you actual look and feel of page. (used for design time data bindings).

2
votes

d:DataContext is for design time. By setting this you will be able to see data coming up in tools like Expression Blend.

The d is from xmlns:d="http://schemas.microsoft.com/expression/blend/2008", normally you also need to include mc:Ignorable="d".

It's also helpful when you want to specify design time width and height for your panel. For example,

d:DesignWidth="1280" d:DesignHeight="812"