The DataContext
The Control.DataContext property describes where controls will look by default for values when binding. The data context will usually be set for top-level controls such as Window and child controls will inherit this data context.
When using the MVVM pattern, the data context will usually be an instance of a view model.
If you created your application with the Avalonia MVVM Application template then you will see something like this in your Program.cs file:
1
private static void AppMain(Application app, string[] args)
2
{
3
var window = new MainWindow
4
{
5
DataContext = new MainWindowViewModel(),
6
};
7
​
8
app.Run(window);
9
}
Copied!
This means that when the MainWindow is created, a new instance of MainWindowViewModel will be created and assigned to the window's DataContext property. From here all bindings will by default bind to properties on this object:
1
<Window>
2
<Button Content="{Binding ButtonCaption}"/>
3
</Window>
Copied!
Will bind the Button's Content to Window.DataContext.ButtonCaption.

Binding DataContext

When binding DataContext, the DataContext of the parent control is used as the source of the binding:
1
<Window>
2
<!-- Will bind `DataContext` to `Window.DataContext.Content -->
3
<StackPanel DataContext="{Binding Content}"/>
4
</Window>
Copied!
Controls that display content based on a data template will automatically set the DataContext for the controls in the template. For example ContentControl:
1
<Window>
2
<ContentControl DataContext="{Binding Content}">
3
<ContentControl.ContentTemplate>
4
<DataTemplate>
5
<!-- Will bind `Text` to `Window.DataContext.Content.Header -->
6
<TextBlock Text="{Binding Header}"/>
7
</DataTemplate>
8
</ContentControl.ContentTemplate>
9
</ContentControl>
10
</Window>
Copied!
Last modified 3mo ago
Export as PDF
Copy link