我遇到问题,使用ScrollViewer
以下是示例视图模型:
public class A
{
public string Text { get; set; }
}
public class B
{
public int Number { get; set; }
}
...和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>
当ListBox
:
如您所见,ScrollViewer
忽略ContentTemplateSelector
,而ContentControl
则忽略ScrollViewer
。 ContentControl
继承自A
,初看起来没有理由这样做。
我知道,如果我要为B
和ScrollViewer
声明隐式数据模板,{{1}}会正确处理它们,但这不是我真实应用的选项。< / p>
这是已知错误吗?或者我错过了什么?
UPD
我已在MS Connect上提交issue。
答案 0 :(得分:1)
我没有测试语法。如果是错的,请告诉我,我会删除
这就是我想要的
<ScrollViewer Grid.Row="1">
<ContentControl Content="{Binding SelectedItem, ElementName=ListBox}"
ContentTemplateSelector="{StaticResource ViewModelTemplateSelectorKey}"/>
</ScrollViewer>
答案 1 :(得分:1)
这应该可以解决问题:
<ScrollViewer Grid.Row="1">
<ContentPresenter Content="{Binding SelectedItem, ElementName=ListBox}" ContentTemplateSelector="{StaticResource ViewModelTemplateSelectorKey}" />
</ScrollViewer>