下列範例示範如何解決當使用 .NET Native 工具鏈編譯的應用程式嘗試繫結資料時擲回的 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" />
程式碼能否重寫以不使用反射?
由於數據系結需要大量反映,因此變更程式碼以避免反映不可行。
不過,有一些方法可以在 XAML 頁面中指定 ViewModel,讓工具鏈環境可以在編譯時期將屬性繫結到正確的類型,並保留元數據而不使用執行時指令。 例如,您可以在屬性上套用 Windows.UI.Xaml.Data.BindableAttribute 屬性。 這會使 XAML 編譯器產生所需的查閱資訊,並避免在 Default.rd.xml 文件中需要運行時指令。