Search code examples
wpfdatatemplateselector

How do I bind a WPF control's content to its container's DataContext so I can apply a DataTemplateSelector based on that object?


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?


Solution

  • 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".