I've faced with issue, using ScrollViewer
.
Here's sample 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 is going on, when any item is selected in ListBox
:
As you can see, ScrollViewer
ignores ContentTemplateSelector
, while ContentControl
does not. ScrollViewer
is inherited from ContentControl
, and at first look, there's no reason for such behavior.
I know, that if I'll declare implicit data templates for A
and B
, ScrollViewer
will handle them correctly, but this is not an option for my real application.
Is this known bug? Or am I missing something?
UPD.
I've submitted an issue on MS Connect.
I did not test the syntax. If it is wrong just let me know and I will delete
This is what I would try
<ScrollViewer Grid.Row="1">
<ContentControl Content="{Binding SelectedItem, ElementName=ListBox}"
ContentTemplateSelector="{StaticResource ViewModelTemplateSelectorKey}"/>
</ScrollViewer>
This should do the trick:
<ScrollViewer Grid.Row="1">
<ContentPresenter Content="{Binding SelectedItem, ElementName=ListBox}" ContentTemplateSelector="{StaticResource ViewModelTemplateSelectorKey}" />
</ScrollViewer>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With