在合并的资源字典中找不到 DataTemplateSelector

DataTemplateSelector not found in merged resource dictionary

我将 CustomDataTemplateSelector 添加到名为 DataTemplates.xaml 的单独文件中的 ResourceDictionary,随后我将其链接到 App.xaml

当我 运行 应用程序时,我收到 XamlParseException 说: 在 xmlns clr-namespace:MyProject

中找不到类型 local:CustomDataTemplateSelector

另一方面,当我将 DataTemplates.xaml 的内容放入 App.xaml 时,它工作得很好。

App.xaml

<Application.Resources>
<ResourceDictionary>
    <ResourceDictionary Source="../DataTemplates.xaml"/>

DataTemplates.xaml

<?xml version="1.0" encoding="UTF-8"?>
<ResourceDictionary
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyProject">

<DataTemplate x:Key="FirstCell">
    <Label Text="Some text"/>
</DataTemplate>

<DataTemplate x:Key="SecondCell">
        <Label Text="Some other text"/>
</DataTemplate>

<local:CustomDataTemplateSelector
    x:Key="CustomDataTemplateSelector"
    SecondTemplate="{StaticResource SecondCell}"
    FirstTemplate="{StaticResource FirstCell}"/>

我已经确认了问题。 (为其他人澄清 - 尝试 运行 应用程序时发生解析错误。在 App.InitializeComponent 期间。)我在 App.xaml 和 [=31] 上都有 xmlns:local ... =].

要解决此问题,请使用替代语法合并词典,ResourceDictionary.MergedDictionaries:

<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
             xmlns:local="clr-namespace:XFSOAnswers"
             x:Class="XFSOAnswers.App">
    <Application.Resources>
        <ResourceDictionary>
            
            <Style TargetType="ContentPage" ApplyToDerivedTypes="True">
                <Setter Property="ios:Page.UseSafeArea" Value="True"/>
            </Style>

            <ResourceDictionary.MergedDictionaries>
                <local:DataTemplates />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

以防万一,这是我对 DataTemplates 的看法:

DataTemplates.xaml:

<?xml version="1.0" encoding="UTF-8"?>
<ResourceDictionary
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XFSOAnswers">

    <DataTemplate x:Key="FirstCell">
        <Label Text="Some text"/>
    </DataTemplate>

    <DataTemplate x:Key="SecondCell">
        <Label Text="Some other text"/>
    </DataTemplate>

    <local:CustomDataTemplateSelector
    x:Key="CustomDataTemplateSelector"
    SecondTemplate="{StaticResource SecondCell}"
    FirstTemplate="{StaticResource FirstCell}"/>

    </ResourceDictionary>

DataTemplates.xaml.cs:

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace XFSOAnswers
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DataTemplates : ResourceDictionary
    {
        public DataTemplates()
        {
        }
    }
}

(原来的Source语法应该不需要这个.cs文件,不知道我用的语法是否需要。)