.Net MAUI クラスライブラリで.NET Community Toolkitを利用すると、「XC0000 Cannot resolve type ~」とエラーになることがあります。当記事では、対処方法を紹介していきます。
紹介環境
当記事は以下の環境で作成しています。
開発環境
- Visual Studio 2022
- .Net 9
発生条件
.Net MAUI クラスライブラリに.NET Community Toolkitのパッケージを追加しただけでは発生しません。以下のように、.NET Community Toolkitを利用したと時に発生します。例では、TouchBehaviorを利用しています。
<?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="SampleLib.SamplePage1"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
Title="SamplePage1">
<Grid>
<Label Text="ここをタップ">
<Label.Behaviors>
<toolkit:TouchBehavior PressedScale="0.5" />
</Label.Behaviors>
</Label>
</Grid>
</ContentPage>
発生したエラーは、以下のようになります。

対応方法
.NET Community Toolkitで利用したい機能を、Resourcesに追加することで対応できます。Resourcesに追加する時は、x:Keyとx:Nameを指定します。
追加した例が、以下のようになります。
<?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="SampleLib.SamplePage1"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
Title="SamplePage1">
<ContentPage.Resources>
<toolkit:TouchBehavior x:Key="TouchBehavior" x:Name="TouchBehavior" />
</ContentPage.Resources>
<Grid>
<Label Text="ここをタップ">
<Label.Behaviors>
<toolkit:TouchBehavior PressedScale="0.5" />
</Label.Behaviors>
</Label>
</Grid>
</ContentPage>
終わりに
XC0000のエラーは、MauiProgramにUseMauiCommunityToolkitを追加し忘れて発生しますが、.Net MAUI クラスライブラリでも発生するとは思いませんでした。.Net MAUI クラスライブラリにMauiProgramはないので、当記事の内容で対応しました。この記事が役に立てば幸いです。