views:

120

answers:

1

I have the following line of code in my code-behind class.

TabControl.ItemsSource = ((MainWindowViewModel)DataContext).TabItemViewModels;

I would like to move this to the XAML file.

In brief,

  • There is a MainWindow class representing the main-window.
  • There is a TabControl placed on the main-window.
  • There are 2 view-models called MainWindowViewModel and TabItemViewModel.
  • MainWindowViewModel has an observable collection of TabItemViewModel classes.
  • MainWindowViewModel is the view-model class for the main window.
  • TabItemViewModel is the view-model class for each individual tab in the TabControl on the main window.
  • The DataContext property of the MainWindow class is set to an instance of the MainWindowViewModel class, instantiated in XAML.

What I want to do is bind the TabItemViewModels property of the MainWindowViewModel class to the ItemSources property of the TabControl.

I am looking for not just a line of code, but also some pointers on the syntax for Bindings as I am totally lost with it and it seems to be pretty crucial to working with XAML.

A: 

First the line of code you're not looking for:

<TabControl ItemsSource="{Binding TabItemViewModels}" ... />

How does this tie into the syntax for bindings? A binding with no Source, ElementName or RelativeSource automatically refers to the DataContext. In your case the MainWindow.DataContext is the MainWindowViewModel that has the TabItemViewModels property. (DataContext propagates down the visual tree, so the TabControl inherits the same DataContext as the containing MainWindow.) So you can just reference that property by name.

For more info and syntax see Data Binding Overview, Binding Sources Overview and Binding Declarations Overview in MSDN.

itowlson