Search code examples
wpfxamlbindingdatacontext

How to do this.DataContext = this: in XAML....for eg<Window.DataContext> <local:MainWindow/></Window.DataContext>-->


Although the result is same after compiling and running the code, I find out that there is a bit difference in design mode in defining the data context behind the XAML in .cs file like below

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainViewModel();
        }   
    }

and doing in a xaml like this.

 <Window.DataContext>
        <local:MainViewModel/>
  </Window.DataContext>

The difference is during design mode in the display window while coding. When the code is in Xaml the view is nice and it shows the elements for eg. for DataGrid its shows the number of rows and column with value its value if its defined.

So, having said that I want to change below code in .cs file to

public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;          
        }

its equivalent in XAML. I tried with the below code

    <Window.DataContext>
        <local:MainWindow/>
    </Window.DataContext>

but it throw exception on Initialization. Can someone please help me with it. I am still new to WPF Databindings Data Context stuff.

Thank You


Solution

  • This sets the DataContext to a new instance of MainWindow (which will in turn set the DataContext to a new instance and so on):

    <Window.DataContext>
        <local:MainWindow/>
    </Window.DataContext>
    

    The equivalent of this.DataContext = this would be: <Window ... DataContext="{Binding RelativeSource={RelativeSource Self}}">.

    You may also set the design time DataContext:

    d:DataContext="{d:DesignInstance Type=local:MainWindow, IsDesignTimeCreatable=True}