Search code examples
c#wpfxamldatacontext

WPF's DataContext questions


I asked about how does it work with INotifyPropertyChanged interface( How does WPF INotifyPropertyChanged work? ), and it requires me to connect XAML's DataContext to the INotifyPropertyChanged inherit instances as follows.

MainViewModel model = new MainViewModel();        
this.DataContext = model;

And I also found a recommendation to have a comment for DataContext that each XMAL uses( http://joshsmithonwpf.wordpress.com/2009/10/24/xaml-tip-datacontext-comment/ ).

When I have multiple XAML files, and when I want to link the DataContext to different ViewModel, I guess I need to make the each XAML.CS file to contain this code (model varies for each xaml.cs) :this.DataContext = model;.

  • Is this correct?
  • How can I do the same thing in XAML file?
  • What's the magic behind this DataContext thing? I mean, how does DataContext work?

Solution

    • Yes that is correct as far as i know, since this is quite repetetive some MVVM frameworks do this linking for you.

    • In XAML:

      <UserControl ...
                   xmlns:vm="clr-namespace:MyApp.ViewModels">
          <UserControl.DataContext>
              <vm:MyViewModel />
          </UserControl.DataContext>
          <!-- ... -->
      </UserControl>
      
    • It enables short bindings where the Path is relative to the DataContext, e.g. {Binding Name} binds to DataContext.Name. It also is inherited which can be useful.

    Please read the Data Binding Overview if you haven't.