Search code examples
c#.netwpf

Setting DataContext in XAML to Window or a property of the Window


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

  1. to the Window itself (not a seperate ViewModel class)

In other words, how can you define this C# code in XAML:

DataContext = this;
  1. or to a property of the Window? (for example, if we want to change the DataContext temporarely to something else only for a single Control like TextBox)

Solution

    1. 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}}"

    2. 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.