C# WinUI 3アプリを作っていく途中で、調べたことを忘録的に投稿します。今回はWinUI3プロジェクトで、Xamlに配置したコントロールで[DataBind]でコンテンツを表示する際に[DataType=”local:xxx”]形式で入力した場合に[XamlCompiler error WMC0909: Cannot resolve Datatype local:xxx’]が表示される場合の対処法です。
Xamlの[DataType]設定
Microsoft 公式の[ツリー ビュー]に公開されているソースコードをコピーしても、エラーになるので困っていました。
例えば、次のXaml編集画面で[DataTemplate]の[DataType]に[.xaml.cs]で定義したクラス名を設定した場合。
<Grid>
<TreeView ItemsSource="{x:Bind DataSource}">
<TreeView.ItemTemplate>
<DataTemplate x:DataType="local:ExplorerItem">
<TreeViewItem ItemsSource="{x:Bind Children}" Content="{x:Bind Name}"/>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
太字の部分に波線が追加されて[型 ‘xxx’ が見つかりません。アセンブリ参照が失われていないか、またすべての参照アセンブリが読み込まれているか確認してください。]が表示されます。
この場合、クラス名の前に親クラスを追加するとエラー表示が無くなります。
<Grid>
<TreeView ItemsSource="{x:Bind DataSource}">
<TreeView.ItemTemplate>
<DataTemplate x:DataType="local:TreeViewApp:ExplorerItem">
<TreeViewItem ItemsSource="{x:Bind Children}" Content="{x:Bind Name}"/>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
しかし、ビルド操作時に[XamlCompiler error WMC0909: Cannot resolve Datatype local:xxx’]エラーで失敗します。
別ファイルでクラスを定義
DataTypeで指定するクラスを別ファイルで定義するとエラーを回避できます。
具体的には次の手順で行います。
1.[ソリューション エクスプローラー]を表示して[プロジェクト]でマウスの右ボタンをクリックして表示されたポップアップメニューで[追加|新しい項目]を選択します。
2. 表示された[新しい項目の追加]画面で[クラス]を選択しファイル名を入力して[追加]をクリックします。
3. 追加されたクラス(拡張子 .cs )ファイルの内容を編集して保存します。
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinUi3Samples
{
// Class to represent items in the TreeView.
public class ExplorerItem
{
// Enum to define the type of the item: Folder or File.
public enum ExplorerItemType
{
Folder,
File,
}
// Name of the item (displayed in the TreeView).
public string Name { get; set; }
// Type of the item (Folder or File).
public ExplorerItemType Type { get; set; }
// Collection of child items. Used for nested nodes in the TreeView.
public ObservableCollection<ExplorerItem> Children { get; set; } = new ObservableCollection<ExplorerItem>();
}
}
実行すると画面に[TreeView]コントロールにデータが配置されて表示されます。
まとめ
今回は短い記事ですが、Visual StudioのWinUI3プロジェクトで、Xamlに追加したTreeViewコントロールの[DataType=”local:xxx”]形式で入力した場合に[XamlCompiler error WMC0909: Cannot resolve Datatype local:xxx’]が表示される場合の対処法を紹介しました。
Xamlと同じファイル名の[.xaml.cs]ファイル内にクラスを追加している場合には別ファイルでクラスを追加してエラーを回避できます。
WinUI 3アプリで[DataType]を設定時に[XamlCompiler error WMC0909: Cannot resolve Datatype local:xxx’]エラーが表示される人の参考になれば幸いです。
スポンサーリンク
最後までご覧いただき、ありがとうございます。