I'm trying to bind a WPF window atop a ViewModel that contains two collections, A and B. I'm attempting to use DataTemplates to display either A or B depending on the setting of a flag in my ViewModel.

To that end, I've set the window's DataContext = ViewModel. However, when I attempt to bind a ContentControl to that DataContext and apply a DataTemplateSelector to it, the item parameter of the selector's SelectTemplate(object item, DependencyObject container) method is always null:

<Window [snip] Title="MainWindow">
    <Window.Resources>
        <!-- DataTemplate and Selector declarations -->
    </Window.Resources>
    <Grid>
        <ContentControl Content="{Binding}"              
                        ContentTemplateSelector="{StaticResource templateSelector}" />
    </Grid>    
</Window>

How should I be binding that ContentControl such that the Window's ViewModel will be passed through to its DataTemplateSelector?

2

There are 2 answers

1
Markus Hütter On BEST ANSWER

this worked for me:

<ContentControl Content="{Binding DataContext, RelativeSource={RelativeSource Self}}"              
                    ContentTemplateSelector="{StaticResource templateSelector}" />

Edit:

I agree with Aaron though, that this might not be the best way to accomplish things. You said you're using a ViewModel. The easiest way would probably be to bind your ItemsControl to a new "SelectedCollection" property on your Viewmodel that exposes the wanted collection. Then in your flag (assuming it is a property) you can fire propertychanged for "SelectedCollection".

1
Aaron McIver On

Lots of things going on here...

You said you are using the DataTemplateSelector to either display collection A or collection B, while at the same time you stated you are setting one of the collections as the DataContext of the Window.

If you want to hide the data in one collection perform filtering on the collection itself. Another approach is to run the binding through an IValueConverter or IMultiValueConverter. Yet another solution could be to have two UI elements bound to each collection respectively and change the Visiblity of the UI element based on the value in your ViewModel.

Lot's of different options...and if I understand you correctly the DataTemplateSelector should not be one of them.