How to associate the contents of a WPF control with its DataContext container so that I can apply a DataTemplateSelector based on this object?

I am trying to link a WPF window on top of a ViewModel that contains two collections: A and B. I am trying to use DataTemplates to display A or B depending on the setting of a flag in my ViewModel.

To this end, I set the DataContext = ViewModel window. However, when I try to associate a ContentControl with this DataContext and apply a DataTemplateSelector to it, the item parameter of the select SelectTemplate(object item, DependencyObject container) method SelectTemplate(object item, DependencyObject container) 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 bind this ContentControl so that the WindowModel is passed into its DataTemplateSelector ?

+4
source share
2 answers

this worked for me:

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

Edit:

I agree with Aaron that this may not be the best way to achieve something. You said you were using ViewModel. The easiest way is to link your ItemControl to the new "SelectedCollection" property on your Viewmodel, which will provide the required collection. Then in your flag (assuming this property) you can run the propertychanged property for "SelectedCollection".

+4
source

A lot is happening here ...

You said you used a DataTemplateSelector to display collection A or collection B, while you stated that you set one of the collections as a DataContext window.

If you want to hide data in one collection, filter the collection itself. Another approach is to start binding through IValueConverter or IMultiValueConverter . Another solution would be to have two interface elements associated with each collection, respectively, and change the Visiblity of the user interface element based on the value in your ViewModel.

Many different options ... and if I understand you correctly, DataTemplateSelector should not be one of them.

+2
source

Source: https://habr.com/ru/post/1340259/


All Articles