示例:在绑定数据时处理异常

以下示例演示如何解析使用 .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" />

代码是否可以重写为不使用反射?

由于数据绑定是反射密集型的,因此更改代码以避免反射是不可行的。

但是,可以通过某些方法将 ViewModel 指定给 XAML 页面,从而使工具链可以在编译时将属性绑定与正确的类型关联,无需使用运行时指令即可保留元数据。 例如,可以将 Windows.UI.Xaml.Data.BindableAttribute 属性应用于属性。 这会导致 XAML 编译器生成所需的查找信息,并避免在 Default.rd.xml 文件中要求运行时指令。

另请参阅