Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When you write</p> <pre><code>&lt;Label name="myLabel" Content="{Binding Path=Name}" /&gt; </code></pre> <p>you are binding to <code>myLabel.DataContext.Name</code>, and not <code>myLabel.Name</code>.</p> <p>The XAML in WPF is just a pretty user interface to display and interact with the actual data, otherwise known as the <code>DataContext</code>. The purpose of other binding sources (<code>RelativeSource</code>, <code>ElementName</code>, etc) is to point to another property that doesn't exist in the current control's <code>DataContext</code> <hr> So suppose you have a Window. Without setting the DataContext, the window still displays but there is no data behind it.</p> <p>Now suppose to set <code>myWindow.DataContext = new ClassA();</code>. Now the data that the window is displaying is <code>ClassA</code>. If <code>ClassA</code> has a property called <code>Name</code>, I could write a label and bind it to <code>Name</code> (such as your example), and whatever value is stored in <code>ClassA.Name</code> would get displayed.</p> <p>Now, suppose <code>ClassA</code> has a property of <code>ClassB</code> and both classes have a property called <code>Name</code>. Here is a block of XAML which illustrates the purpose of the DataContext, and an example of how a control would refer to a property not in it's own DataContext</p> <pre><code>&lt;Window x:Name="myWindow"&gt; &lt;!-- DataContext is set to ClassA --&gt; &lt;StackPanel&gt; &lt;!-- DataContext is set to ClassA --&gt; &lt;!-- DataContext is set to ClassA, so will display ClassA.Name --&gt; &lt;Label Content="{Binding Name}" /&gt; &lt;!-- DataContext is still ClassA, however we are setting it to ClassA.ClassB --&gt; &lt;StackPanel DataContext="{Binding ClassB}"&gt; &lt;!-- DataContext is set to ClassB, so will display ClassB.Name --&gt; &lt;Label Content="{Binding Name}" /&gt; &lt;!-- DataContext is still ClassB, but we are binding to the Window's DataContext.Name which is ClassA.Name --&gt; &lt;Label Content="{Binding ElementName=myWindow, Path=DataContext.Name}" /&gt; &lt;/StackPanel&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>As you can see, the DataContext is based on whatever data is behind the UI object.</p> <p><strong>Update:</strong> I see this question so often from new WPF users that I expanded this answer into a post on my blog: <a href="http://rachel53461.wordpress.com/2012/07/14/what-is-this-datacontext-you-speak-of/" rel="noreferrer">What is this “DataContext” you speak of?</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload