当我运行我的应用程序时,我没有使用数据模板,而是看到控件中显示的视图模型的完整类名。 MyDataTemplateSelector 类已实例化,但 SelectTemplateCore 从未被调用。我也没有得到第一次机会例外。
public class MyDataTemplateSelector : DataTemplateSelector
{
public DataTemplate Normal { get; set; }
protected override DataTemplate SelectTemplateCore(object item)
{
return this.Normal;
}
}
<Window
x:Class="Adventure.WinUi.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Adventure.WinUi"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:adventure="using:Adventure"
mc:Ignorable="d"
x:Name="ThisPage">
<StackPanel>
<StackPanel.Resources>
<DataTemplate x:Key="SceneDefault" x:DataType="local:AdventureViewModel">
<TextBlock>Blabla</TextBlock>
</DataTemplate >
<local:MyDataTemplateSelector x:Key="MyDataTemplateSelector" Normal="{StaticResource SceneDefault}" />
</StackPanel.Resources>
<ContentControl ContentTemplateSelector="{StaticResource MyDataTemplateSelector}" Content="{x:Bind ViewModel, Mode=OneWay}" />
</StackPanel>
</Window>
doc对此没有多大帮助。因此,尝试覆盖另一个:
protected override DataTemplate? SelectTemplateCore(object item, DependencyObject container)
{
return this.Normal;
}