I want the TemplateSelector to select a template based on the country.
So, for MyDataTemplateSelector:SelectTemplate to receive the country I bind Content of ContentPresenter to CountriesComboBox.
The problem is that the returned template is not bound to City or Streets. I think it happens because DataContext of the selected template is not bound to the ViewModel, and thus, bounded properties of the tamplate are not accessible.
I tried the code below, but in my opinion, it doesn't work since the Content of ContentPresenter is bound to CountriesComboBox and not to {Binding} as it should be. But, if I bind Content to {Binding}, I won't have access to the selected item of CountriesComboBox from TemplatrSelector.
So, how do I do this?
<DataGrid>
<DataGrid.Resources>
<DataTemplate x:Key="Readonly_CellEditingTemplate">
<TextBlock Text="{Binding City}"/>
</DataTemplate>
<DataTemplate x:Key="Editable_CellEditingTemplate">
<ComboBox ItemsSource="{Binding Streets}" />
</DataTemplate>
<local:MyDataTemplateSelector ReadonlyTemplate="{StaticResource Readonly_CellEditingTemplate}" EditableTemplate="{StaticResource Editable_CellEditingTemplate}" x:Key="MyDataTemplateSelector"/>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Header="City">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding City}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ContentPresenter x:Name="Presenter" Content="{Binding ElementName=CountriesComboBox, Path=SelectedIndex}" ContentTemplateSelector="{StaticResource MyDataTemplateSelector}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<ComboBox Name="CountriesComboBox" ItemsSource="{Binding Countries}" />
I've found an answer in 3 years old post from Victor. Thanks Victor. I just need to add
DataContext="{Binding RelativeSource={RelativeSource AncestorType=ContentControl},Path=DataContext}"in eachDataTemplate.