When we are setting DataContext inside XAML to a ViewModel, we use either this:
<Window.DataContext>
<local:MyViewModel/>
</Window.DataContext>
or binding it inside a tag to a StaticResource.
(Assuming someone doesn't use a framework like Prism)
But, is it possible to set the DataContext via XAML
In other words, how can you define this C# code in XAML:
DataContext = this;
You can set a Window
's DataContext
to the Window
itself like that (Add that line to your Window
's properties in the XAML):
DataContext="{Binding RelativeSource={RelativeSource Self}}"
After binding the Window
to itself as DataContext
, you can already use the properties of the Window
, so you may not need to bind to a property.