c# - 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
文件存在于所有项目中。
解决方案
我在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 版替换了这个包,一切都很好。
推荐阅读
- c# - MSBuild 在构建项目时查找 Main
- java - 生成随机数并在条件为真时打印的循环
- sql-server-2014 - 导入 psv 文件时出现 SQL 导入向导错误
- python - 如何创建一个不断更新的全局变量?
- php - PHP MySql 时间计算
- javascript - RxJS:禁止在效果和史诗中使用不安全的 catch 并请求嵌套
- c# - Blazor Swagger:无法加载 API 定义。获取错误:未定义 /swagger/v1/swagger.json
- javascript - 通过从 Firebase 存储访问来更新用户的 photoURL
- api - 存储 API 密钥
- javascript - 如何将孩子添加到具有唯一名称的 firebase 数据列表中?