0
votes

I am designing a WPF Application and have the following ViewModels:

  • ProjectViewModel (contains an ObservableCollection of GroupViewModels)
  • GroupViewModel (contains an ObservableCollection of ItemViewModels)
  • ItemViewModel

I was planning on representing this with a Window that contains multiple Tabs that contain Items.

Here's how it will look:

enter image description here

In my MainWindow.xaml:

<Window.DataContext>
    <viewModel:ProjectViewModel/>
</Window.DataContext>

I was planning on binding ViewModel to View UIElements as follows:

  • ProjectViewModel -> (bound to) Window
  • GroupViewModel -> (bound to) TabItem
  • ItemViewModel -> (bound to) some custom control, just shown as a colored rectangle for now

Here's the problem I can't figure out ...

The Tabs need to be dynamic (can be added/deleted by the user).

In order to accomplish this, I followed a tutorial on CodeProject.com: Add/Remove Tabs Dynamically in WPF.

In this code, TabControl.DataContext is set to a List of TabItems that has items added/removed based on user actions.

However, if I bind TabControl.DataContext to a List of TabItems, won't I lose the ability to bind it to my GroupViewModel?

Is there a way to bind it to both?

Following MVVM pattern, isn't a UIElement's DataContext supposed to be bound to a ViewModel, not to another UIElement.

Is there a way I can bind my ViewModels to my View UIElements as I had planned and still do the dynamic tabs?

Thank you very much for any ideas or suggestions.

Philip

1

1 Answers

3
votes

It is not necessary to bound each nested collection to the nested element of visual tree. The DataContext dependency property inherits through that tree.

<Window.DataContext>
    <viewModel:ProjectViewModel/>
</Window.DataContext>
<TabControl
        ItemsSource="{Binding GroupViewModels}">
....