.NET MAUI 库:XamlC 错误 XFC0000:无法解析类型

Bra*_*ick 3 .net c# xaml maui maui-community-toolkit

当使用 Visual Studio 构建包含对 .NET MAUI Community Toolkit 的 IsEqualConverter引用的 .NET MAUI 库时,Visual Studio 输出窗口中会显示以下错误:

XamlC 错误 XFC0000:无法解析类型“http://schemas.microsoft.com/dotnet/2022/maui/toolkit:mct:IsEqualConverter”。

尝试在类库中使用其他 .NET MAUI Community Toolkit 转换器时也会出现此问题。

重现步骤

  1. 从 Visual Studio 中的重现存储库中打开解决方案。
  2. 尝试构建该项目。如果存在问题,XamlC error XFC0000: Cannot resolve type每个目标平台的 VS 输出窗口中都会报告错误。

链接到公共复制项目存储库

https://github.com/awalker-dsg/MauiLibTestLib_ConverterIssue

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiLibTestLib_ConverterIssue.Views.IsEqualConverterPage"
             xmlns:mct="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             Title="IsEqualConverterPage">
    <ContentPage.Resources>
        <x:String x:Key="MAUI">MAUI</x:String>
        <mct:IsEqualConverter x:Key="IsEqualConverter" />        
    </ContentPage.Resources>

    <!-- 
        The code in VerticalStackLayout was taken from the MAUI community toolkit sample code here:
        https://github.com/CommunityToolkit/Maui/blob/main/samples/CommunityToolkit.Maui.Sample/Pages/Converters/IsEqualConverterPage.xaml
    -->
    <VerticalStackLayout Spacing="10">
        <Label Text="The IsEqualConverter is a converter that allows users to convert any value binding to a bool depending on whether or not it is equal to a different value. The initial binding contains the object that will be compared and the ConverterParameter contains the object to compare it to."/>
        <Entry Margin="0"
                    Text="{Binding InputValue}" 
                    HorizontalOptions="FillAndExpand"/>
        <Label Text="Does the entry text equal &quot;MAUI&quot;?"/>
        <Label FontSize="Large" 
                    HorizontalOptions="FillAndExpand"
                    Text="Yes, it does!"
                    TextColor="Green">
            <Label.Triggers>
                <DataTrigger TargetType="Label"
                                    Binding="{Binding InputValue, Converter={StaticResource IsEqualConverter}, ConverterParameter={StaticResource MAUI}}"
                                    Value="False">
                    <Setter Property="Text" Value="No, it doesn't" />
                    <Setter Property="TextColor" Value="Red" />
                </DataTrigger>
            </Label.Triggers>
        </Label>
    </VerticalStackLayout>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)

Bra*_*ick 12

链接正在从您的项目中删除我们的库。当编译器删除“未使用的”第三方库时,就会发生这种情况,这是因为链接器不够智能,无法理解 XAML 中正在使用该库(它只知道如何扫描 C# 代码)。

解决方法

更新您的 XAML 代码以添加x:Name这将为代码隐藏中的行为生成 C# 属性;在编译期间,链接器现在将看到您正在使用CommunityToolkit.Maui并且将不再删除它:

<mct:IsEqualConverter x:Key="IsEqualConverter" x:Name="IsEqualConverter"/>
Run Code Online (Sandbox Code Playgroud)