ScrollViewer ignores ContentTemplateSelector

I ran into a problem using ScrollViewer .
Here are examples of view models:

 public class A { public string Text { get; set; } } public class B { public int Number { get; set; } } 

... and DataTemplateSelector :

 public class ViewModelTemplateSelector : DataTemplateSelector { public DataTemplate ATemplate { get; set; } public DataTemplate BTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item is A) return ATemplate; if (item is B) return BTemplate; return base.SelectTemplate(item, container); } } 

XAML:

 <Grid> <Grid.Resources> <local:ViewModelTemplateSelector x:Key="ViewModelTemplateSelectorKey"> <local:ViewModelTemplateSelector.ATemplate> <DataTemplate> <TextBlock Text="{Binding Text}"/> </DataTemplate> </local:ViewModelTemplateSelector.ATemplate> <local:ViewModelTemplateSelector.BTemplate> <DataTemplate> <TextBox Text="{Binding Number}"/> </DataTemplate> </local:ViewModelTemplateSelector.BTemplate> </local:ViewModelTemplateSelector> </Grid.Resources> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <ListBox x:Name="ListBox" ItemsSource="{Binding}"/> <ScrollViewer Grid.Row="1" Content="{Binding SelectedItem, ElementName=ListBox}" ContentTemplateSelector="{StaticResource ViewModelTemplateSelectorKey}"/> <ContentControl Grid.Row="2" Content="{Binding SelectedItem, ElementName=ListBox}" ContentTemplateSelector="{StaticResource ViewModelTemplateSelectorKey}"/> </Grid> 

This is what happens when an item is selected in a ListBox :

enter image description here

As you can see, ScrollViewer ignores ContentTemplateSelector , but ContentControl does not. ScrollViewer inherits from ContentControl and, at first, there is no reason for this behavior.

I know that if I declare implicit data patterns for A and B , ScrollViewer will handle them correctly, but this is not an option for my real application.

Is this a known bug? Or am I missing something?

UPD

I sent a question to MS Connect.

+5
source share
2 answers

I have not tested the syntax. If this is wrong, just let me know and I will delete
This is what I would like to try

 <ScrollViewer Grid.Row="1"> <ContentControl Content="{Binding SelectedItem, ElementName=ListBox}" ContentTemplateSelector="{StaticResource ViewModelTemplateSelectorKey}"/> </ScrollViewer> 
+1
source

This should do the trick:

  <ScrollViewer Grid.Row="1"> <ContentPresenter Content="{Binding SelectedItem, ElementName=ListBox}" ContentTemplateSelector="{StaticResource ViewModelTemplateSelectorKey}" /> </ScrollViewer> 
+1
source

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


All Articles