我开始使用Realm,我正在尝试将Realm数据库中的集合绑定到ListView
。绑定工作正常,但添加新项目时我的ListView
不会更新。我的理解是IRealmCollection<>
实现了INotifyCollectionChanged
和INotifyPropertyChanged
事件。
这是一个重现问题的简单应用程序:
View
:
<Page x:Class="App3.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:App3"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<Button Click="ButtonBase_OnClick" Content="Add" />
<ListView x:Name="ListView">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Id}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Grid>
</Page>
CodeBehind
:
namespace App3
{
public class Thing : RealmObject
{
public string Id { get; set; } = Guid.NewGuid().ToString();
}
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private Realm _realm;
private IRealmCollection<Thing> things;
public MainPage()
{
this.InitializeComponent();
_realm = Realm.GetInstance();
things = (IRealmCollection<Thing>)_realm.All<Thing>();
ListView.ItemsSource = things;
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
_realm.Write(() =>
{
var thing = new Thing();
_realm.Add(thing);
});
}
}
}
我通常使用MVVM(Template10),但这是一个简单的应用程序来演示这个问题。单击Add
按钮会将项添加到数据库,但ListView
仅在首次加载应用程序时更新。我已经阅读过类似的问题,但我还没有找到一个有效的答案。 Inverse Relationships and UI-Update not working?是我发现的最接近的,但仍无法解决问题。
修改
我可以强迫它像这样重新绑定:
ListView.ItemsSource = null;
ListView.ItemsSource = things;
但这不是最佳的。我试图利用Realm&#34;&#34; live objects&#34;集合应始终知道何时更改或添加项目。
编辑2
在代码隐藏中设置BindingMode=OneWay
也不会改变行为:
_realm = Realm.GetInstance();
things = (IRealmCollection<Thing>)_realm.All<Thing>();
var binding = new Binding
{
Source = things,
Mode = BindingMode.OneWay
};
ListView.SetBinding(ListView.ItemsSourceProperty, binding);
解
结果证明IRealmCollection
:https://github.com/realm/realm-dotnet/issues/1461#issuecomment-312489046中的已知问题已在Realm 1.6.0中得到修复。我已更新到预发布的NuGet包,可以确认ListView
现在按预期更新。
答案 0 :(得分:1)
在Mode=OneWay
Binding
<ListView ItemsSource="{x:Bind things, Mode=OneWay}" />
Binding myBind = new Binding();
myBind.Source = things;
myBind.Mode = BindingMode.OneWay;
myListView.SetBinding(ListView.ItemsSourceProperty, myBind);
这是IRealmCollection中的一个错误。您可以使用Prerelease Nuget来解决此问题。
了解更多信息:
IRealmCollection does not update UWP ListView
GitHub Issue: IRealmCollection does not update UWP ListView