C# ListView未在CollectionChanged上更新
我开始使用Realm,并尝试将Realm数据库中的集合绑定到C# ListView未在CollectionChanged上更新,c#,xaml,uwp,realm,C#,Xaml,Uwp,Realm,我开始使用Realm,并尝试将Realm数据库中的集合绑定到列表视图。绑定工作正常,但添加新项时,myListView不会更新。我的理解是,IRealmCollection实现了INotifyCollectionChanged和INotifyPropertyChanged事件 下面是一个简单的应用程序来重现该问题: 视图: <Page x:Class="App3.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/x
列表视图
。绑定工作正常,但添加新项时,myListView
不会更新。我的理解是,IRealmCollection
实现了INotifyCollectionChanged
和INotifyPropertyChanged
事件
下面是一个简单的应用程序来重现该问题:
视图
:
<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>
我通常使用MVVM(Template10),但这是一个简单的应用程序来演示这个问题。单击添加
按钮将一个项目添加到数据库中,但列表视图仅在首次加载应用程序时更新。我读过类似的问题,但我还没有找到一个有效的答案。是我找到的最接近的,但仍然无法解决问题
编辑
我可以强迫它像这样重新绑定:
ListView.ItemsSource = null;
ListView.ItemsSource = things;
但这并不是最优的。我试图利用Realm的“活动对象”,在这里集合应该总是知道项目何时被更改或添加
编辑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);
\u realm=realm.GetInstance();
things=(IRealmCollection)\u realm.All();
var绑定=新绑定
{
来源=事物,
Mode=BindingMode.OneWay
};
SetBinding(ListView.ItemsSourceProperty,绑定);
解决方案
这是IRealmCollection
中的一个已知问题:已在领域1.6.0中修复。我已经更新了预发布的NuGet软件包,可以确认列表视图现在已按预期更新。在绑定中设置模式=单向
方法1:在Xaml中
这是IRealmCollection中的一个bug。你可以用它来解决它
有关更多信息:
试试我发布的这个。可能适用于您的情况项目已添加到数据库,但您用作ListView项目源的“things”集合不知道已添加的新项目。因此,您需要从数据库中重新查询新项目,并将其加载到“things”集合中。@没有人运气好。UpdateLayout
方法没有什么区别,而且它看起来似乎对UWP不存在InvalidateVisual
。TextBlock
绑定不会影响ListView.ItemsSource
绑定。将列表视图
的绑定更改为单向
也不会更改行为。请对列表视图
使用模式=单向
。到目前为止,我已经更新了我的答案,我唯一能更新列表视图的方法是将项目资源设置为null
,然后重新绑定。请参阅更新的问题。是的,它没有改变任何内容。似乎CollectionChanged没有启动或类似于通知ListView
刷新ItemsSource
…@dubstylee为您的INotifyCollectionChanged添加一些示例代码
_realm = Realm.GetInstance();
things = (IRealmCollection<Thing>)_realm.All<Thing>();
var binding = new Binding
{
Source = things,
Mode = BindingMode.OneWay
};
ListView.SetBinding(ListView.ItemsSourceProperty, binding);
<ListView ItemsSource="{x:Bind things, Mode=OneWay}" />
Binding myBind = new Binding();
myBind.Source = things;
myBind.Mode = BindingMode.OneWay;
myListView.SetBinding(ListView.ItemsSourceProperty, myBind);