例:データ バインド時の例外の処理

次の例は、.NET ネイティブ ツール チェーンでコンパイルされたアプリがデータをバインドしようとしたときにスローされる MissingMetadataException 例外の解決方法を示しています。 例外情報は次のとおりです。

This operation cannot be carried out as metadata for the following type was removed for performance reasons:
App.ViewModels.MainPageVM

関連付けられている呼び出し履歴は次のとおりです。

Reflection::Execution::ReflectionDomainSetupImplementation.CreateNonInvokabilityException+0x238
Reflection::Core::ReflectionDomain.CreateNonInvokabilityException+0x2e
Reflection::Core::Execution::ExecutionEnvironment.+0x316
System::Reflection::Runtime::PropertyInfos::RuntimePropertyInfo.GetValue+0x1cb
System::Reflection::PropertyInfo.GetValue+0x22
System::Runtime::InteropServices::WindowsRuntime::CustomPropertyImpl.GetValue+0x42
App!$66_Interop::McgNative.Func_IInspectable_IInspectable+0x158
App!$66_Interop::McgNative::__vtable_Windows_UI_Xaml_Data__ICustomProperty.GetValue__STUB+0x46
Windows_UI_Xaml!DirectUI::PropertyProviderPropertyAccess::GetValue+0x3f
Windows_UI_Xaml!DirectUI::PropertyAccessPathStep::GetValue+0x31
Windows_UI_Xaml!DirectUI::PropertyPathListener::ConnectPathStep+0x113

アプリは何をしていたのか?

スタックの最下位にある Windows.UI.Xaml 名前空間のフレームは、XAML レンダリング エンジンが実行されていたことを示します。 PropertyInfo.GetValue メソッドの使用は、そのメタデータが削除された型での、プロパティ値のリフレクションベースのルックアップを示します。

メタデータ ディレクティブを提供するための最初の手順は、型の serialize メタデータを追加して、そのプロパティすべてをアクセス可能にすることです。

<Type Name="App.ViewModels.MainPageVM" Serialize="Required Public" />

特殊なケースかどうか

このシナリオでは、ある ViewModel について、データ バインディングに不完全なメタデータが含まれる場合、他のものにも同じことが該当する可能性があります。 アプリのビュー モデルがすべて App.ViewModels 名前空間内にあるようにコードが作成されている場合、より一般的なランタイム ディレクティブを使用できます。

<Namespace Name="App.ViewModels " Serialize="Required Public" />

リフレクションを使用しないようにコードを書き換えることができるか

データ バインディングではリフレクションが多用されるため、リフレクションを使用しないようにコードを変更することはできません。

ただし、ViewModel を XAML ページに指定して、ツール チェーンがコンパイル時にプロパティ バインディングを正しい型に関連付けて、ランタイム ディレクティブを使用せずにメタデータを保持できるようにする方法はあります。 たとえば、プロパティに Windows.UI.Xaml.Data.BindableAttribute 属性を適用できます。 これにより、XAML コンパイラが必要なルックアップ情報を生成するようになり、Default.rd.xml ファイルのランタイム ディレクティブが不要になります。

関連項目