Der DataContext kann auf verschiedene Arten an verschiedenen Stellen erstellt werden (was es nicht gerade leichter macht, den Gesamtüberblick zu behalten):
DataContext via Window.DataContext
<Window x:Class="SampleApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" DataContext="{Binding Employee}">
bzw.
<Window x:Class="Example.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:l="clr-namespace:Example" Title="Example" Height="300" Width="300" Name="Main">
<Window.DataContext>
<StaticResource ResourceKey="data"/>
</Window.DataContext>
Ziemlich gute Darstellung des Zusammenspiels von Window.DataContext, Window.Resources und einem WPF-Control: http://stackoverflow.com/a/1959701/1777526
DataContext in einem untergeordneten WPF-control
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
DataContext in der Codebehind-Datei
public MainWindow()
{
(...)
gridOfNames.DataContext = new ParameterDataSource();
(...)
}
Häufig wird die zu entwickelnde GUI selbst als DataContext gesetzt, wobei es zwei Wege gibt:
1.) im XAML
<Window x:Class="MyClass"
Title="{Binding windowname}"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Height="470" Width="626">
2.) im Codebehind
public class MyWindow : Window {
public MyWindow() {
InitializeComponents();
DataContext = this;
}
}
Weiterführende Quelle mit gutem Anwendungsbeispiel
Binding-Quellen jenseits vom DataContext
<Window x:Class="WpfTutorialSamples.DataBinding.HelloBoundWorldSample" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="HelloBoundWorldSample" Height="110" Width="280">
<StackPanel Margin="10">
<TextBox Name="txtValue" />
<WrapPanel Margin="0,10">
<TextBlock Text="Value: " FontWeight="Bold" />
<TextBlock Text="{Binding Path=Text, ElementName=txtValue}" />
</WrapPanel>
</StackPanel>
</Window>
… oder mit dem Source-Property, welches z.B. zu einer Window.Ressource bindet:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:SDKSample"
SizeToContent="WidthAndHeight"
Title="Simple Data Binding Sample">
<Window.Resources>
<src:Person x:Key="myDataSource" PersonName="Joe"/>
</Window.Resources>
(...)
<TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=PersonName}"/>
(...)
</Window>