我正在开发一个带有 GridView 的 UWP 项目,我希望根据数据动态填充不同的项目模板。
MainPage.xaml:
<GridView HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Margin="80, 40, 60, 40" BorderThickness="0"
ItemsSource="{x:Bind Favorites}"
ItemTemplateSelector="{StaticResource ItemTemplateSelector}">
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="Margin" Value="0, 0, 0, 32"/>
</Style>
</GridView.ItemContainerStyle>
</GridView>
<Page.Resources>
<local:ItemTemplateSelector x:Key="ItemTemplateSelector"
Template1="{StaticResource Template1}"
Template2="{StaticResource Template2}">
</local:ItemTemplateSelector>
<DataTemplate x:Key="Template1" x:DataType="data:Test1" >
<local:Template1 HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></local:Template1>
</DataTemplate>
<DataTemplate x:Key="Template2" x:DataType="data:" >
<local:Template2 HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></local:Template2>
</DataTemplate>
</Page.Resources>
ItemTemplateSelector.cs:
public class ItemTemplateSelector: DataTemplateSelector
{
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
if (item is Test1)
{
return Template1;
}
else if (item is Test2)
{
return Template2;
}
else
{
return base.SelectTemplateCore(item);
}
}
public DataTemplate Template1 { get; set; }
public DataTemplate Template2 { get; set; }
}
问题是,当我尝试运行应用程序时,出现以下错误:
Windows.UI.Xaml.Markup.XamlParseException: 'The text associated with this error code could not be found.
Cannot find a Resource with the Name/Key ItemTemplateSelector [Line: 66 Position: 19]'