WPF - 重新加载集合(使用“new”),无需重新绑定控件
想象一下以下情况:
class Repository
{
private ObservableCollection<ModelClass> _allEntries;
public ObservableCollection<ModelClass> AllEntries
{
get { return _allEntries; }
set { _allEntries = value; }
}
public void RefreshDataFromDB()
{
_all = new ObservableCollection(GetMyData()); // whatever method there is
}
}
现在有几个控件绑定到该集合,例如:
<ListView ItemsSource="{Binding Repository.AllEntries, ElementName=Whatever}"/>
现在的问题是,如果我调用 RefreshDataFromDB
,绑定就会丢失(至少看起来如此),因为 _all现在指向新的内存部分,并且绑定仍然使用旧的引用。在这种情况下,INotifyPropertyChanged
对我没有帮助(例如,将其放在 RefreshDataFromDB
中并没有多大帮助)。
问题是 - 您将如何处理替换集合并想要更新其使用者绑定的情况?
Imagine the following:
class Repository
{
private ObservableCollection<ModelClass> _allEntries;
public ObservableCollection<ModelClass> AllEntries
{
get { return _allEntries; }
set { _allEntries = value; }
}
public void RefreshDataFromDB()
{
_all = new ObservableCollection(GetMyData()); // whatever method there is
}
}
Now there are a couple of controls that bind to this collection, e.g.:
<ListView ItemsSource="{Binding Repository.AllEntries, ElementName=Whatever}"/>
The problem now is that if I call the RefreshDataFromDB
the bindings get lost (at least it seems so) as the _all is now pointing to new memory part and the bindings still use the old reference. INotifyPropertyChanged
does not help me in this case (e.g. putting it in RefreshDataFromDB
does not help a lot).
The question would be - how would you handle a case where you replce a collection and want to update its consumers' bindings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的;您不修改该集合,UI 绑定到该集合,然后用一个新集合替换它。
你可以这样做:
希望有帮助!
或者,将 AllEntries (或 All.. 您的命名法似乎在帖子中更改了几次;))作为 DependencyProperty:
您还需要创建 get/set 属性,请参阅此处的示例:
Yes; you're not modifying the collection, the UI is bound to the collection, and then you replace it with a new one.
You could do this:
Hope that helps!
Alternatively, make AllEntries (or All.. your nomenclature seems to change a few times on the post ;)) a DependencyProperty:
You'd need to make the get/set property too, see here for an example: