C# WinUI 3アプリを作っていく途中で、調べたことを忘録的に投稿します。今回はWinUI3プロジェクトで、Xamlに配置したコントロールで[DataBind]でコンテンツを表示する際に[DataType=”local:xxx”]形式でネストした下部のクラスを入力した際に[XamlCompiler error WMC0909: Cannot resolve Datatype local:xxx’]が表示される場合の対処法です。
Xamlの[DataType]設定
Xaml編集画面で[DataTemplate]の[DataType]に[.xaml.cs]で定義したクラス名を設定する場合、こんな感じで “local:xxx” 形式で入力します。
<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>
メインの画面から表示した別画面など、他クラス内で定義したクラスを指定する場合、コロン[:]やプラス[+]で繋げることが可能なようです。
<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に配置したコントロールで[DataBind]でコンテンツを表示する際に[DataType=”local:xxx”]形式でネストした下部のクラスを入力した際に[XamlCompiler error WMC0909: Cannot resolve Datatype local:xxx’]が表示される場合の対処法を紹介しました。
[DataType]に入力する際に “local:[親クラス]:[子クラス]” のように[:]や[+]記号でクラス名を連結させてネストすることで編集時はエラーなく入力ができますが、ビルド時にエラーになります。
エラーになる場合は、別ファイルでクラスを定義することで回避することが可能です。
WinUI 3アプリで[DataType]を設定時にネストしたクラスで[XamlCompiler error WMC0909: Cannot resolve Datatype local:xxx’]エラーが表示される人の参考になれば幸いです。
スポンサーリンク
最後までご覧いただき、ありがとうございます。