在 XAML 中使用 Xamarin.Forms.Behaviors 会在 iOS 中导致 TargetInvocationException,但在 Android 中不会

Using Xamarin.Forms.Behaviors in XAML causes TargetInvocationException in iOS but not in Android

我正在做一个 Xamarin.Forms 应用程序,我需要使用行为。 I have added the Xamarin.Forms.Behaviors package to the project and added a behavior to the XAML of one page, so a command is executed when the selection of a ListView changes:

<b:Interaction.Behaviors>
    <b:BehaviorCollection>
        <b:EventToCommand Command="{Binding ItemSelectedCommand}" EventName="ItemSelected" />
    </b:BehaviorCollection>
</b:Interaction.Behaviors>

这在 Android 上运行良好,但同一个项目在导航到 iOS 下的同一页面时抛出 TargetInvocationException。可能是什么原因造成的?

Xamarin 的 iOS 链接器在剥离它认为未使用或引用的 symbols/types 时更具攻击性;而 Xamarin.Forms XAML 通常是这个过程的受害者。

有两个选项可以解决这个问题: - 更改链接器的剥离模式(右键单击 Xamarin.iOS 项目 -> Properties -> iOS Build 选项卡 -> 将 Linker behavior 设置为 Link SDK assemblies onlyDon't link).这将确保在创建应用程序包时删除最少数量的符号(或根本 none),缺点是应用程序大小会急剧增加。 - 创建一个手动引用这些类型的代码文件(例如创建未使用的实例),这样它们就不会被自动剥离。 MvvmCross use this approach.

这样的库

推荐使用后一种方法,尽管它需要做更多的工作。当您使用第三方库时应该使用前者,其中有很多类型正在被剥离,并且需要更多的工作来引用所有这些库。