【问题标题】:Realm 2-way binding in Xamarin Forms UWP throws exceptionXamarin Forms UWP 中的领域 2 路绑定引发异常
【发布时间】:2019-10-30 09:07:44
【问题描述】:

我正在开发针对 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 文件。

【问题讨论】:

  • 我用 RealM 4.0 nuget 创建了一个代码示例,它运行良好。这是测试sample
  • @NicoZhu-MSFT 谢谢,就是这样。

标签: c# xaml xamarin.forms uwp realm


【解决方案1】:

我在 Realm.Net 库的official github issues 中收到了对此问题的回复。

双向数据绑定不适用于带有 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 版替换了这个包,一切就正常了。

【讨论】:

    猜你喜欢
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    相关资源
    最近更新 更多