首页 > 解决方案 > Xamarin Forms UWP 中的领域 2 路绑定引发异常

问题描述

我正在开发针对 iOS/Droid/UWP 的 Xamarin 表单项目。我们正在以反应方式构建应用程序并使用直接模型绑定。例如,假设我们有以下代码

public class Product : RealmObject
    {
        public string Name { get; set; }
    }
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public static string LocalPath = "";
        public MainPage()
        {
            InitializeComponent();
            var realm = Realm.GetInstance(Path.Combine(LocalPath, "RealmSample.realm"));
            realm.Write(() =>
            {
                realm.Add(new Product()
                {
                    Name = "Test"
                });
            });
            BindingContext = realm.All<Product>().FirstOrDefault();
        }
    }

以及以下 xaml 文件

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="RealmBindingSample.MainPage">

    <StackLayout>
        <Entry 
            Text="{Binding Name}"/>
    </StackLayout>

</ContentPage>

这里没有什么特别的。并且此代码在 iOS/Droid 上运行良好,并且只要条目的值发生变化,数据就会保持不变。但是,在加载页面后,在 UWP 上,我得到以下异常

无法在写事务之外修改托管对象。

这是 UWP 中的预期行为吗?我是不是错过了什么。

我已经安装了 Realm.Database nuget 3.4.0 版,并且FodyWeavers.xml文件存在于所有项目中。

标签: c#xamlxamarin.formsuwprealm

解决方案


我在Realm.Net 库的官方 github 问题中得到了对此问题的回复。

双向数据绑定不适用于带有 Realm 3.4.0 的 UWP,因为它是 netstandard 1.4 库,并且实现自动事务所需的类仅在 netstandard 2.0 中添加。您可以将 Realm 升级到 4.0.0,但请注意,这需要将您的 UWP 项目升级到以 netstandard 2.0 为目标。

问题出在我使用的 Realm nuget 包的版本中。我使用 Realm.Database nuget 最新的 3.4.0 版本。一旦我用 Realm nuget 4.0.0 版替换了这个包,一切都很好。


推荐阅读