简体   繁体   English

打开和关闭绑定

[英]Turn the binding on and off

Suppose you have a ViewModel with an ObservableCollection (OC) that is bound to some control inside the View. 假设您有一个带有ObservableCollection(OC)的ViewModel,该模型绑定到View内的某些控件。

Is there a way to temporarily disable the binding between the OC and the Control without removing the binding ? 有没有一种方法可以在不删除绑定的情况下临时禁用OC和控件之间的绑定? I want to have the ability to modify my ObservableCollection without having the View being informed of it. 我希望能够在不通知View的情况下修改我的ObservableCollection。

The reason for that is simple: I am doing a lot of Add() and Insert() operations on the OC. 这样做的原因很简单:我在OC上做了很多Add()和Insert()操作。 Most of the time everything is OK but sometimes I am calling Add() so frequently that the updates in the View are looking unpleasant. 在大多数情况下,一切正常,但有时我经常调用Add(),以至于视图中的更新看起来不愉快。 For these periods of time I want to 'switch off' the binding beforehand and 'turn it on' afterwards. 在这些时间段内,我想先“关闭”装订,然后再“打开”装订。

Has anybody been in a similar situation / does anybody has a tip ? 是否有人处于类似情况/有人给小费吗?

只需包装ObservableCollection (甚至继承自ObservableCollection ),然后通过添加自定义逻辑来覆盖mthod OnCollectionChanged ,这将考虑您的要求推迟事件触发,我相信这是实现自己的可观观察性集合的相当标准的方法。

When I have a lot of items in the collection, I prefer to use a List<> as the source of a CollectionViewSource. 当集合中有很多项目时,我更喜欢使用List <>作为CollectionViewSource的源。 Then the view binds to the CollectionViewSource.View. 然后,视图绑定到CollectionViewSource.View。 CollectionViewSource has methods DeferRefresh() and Refresh() that let you do all the background work of changing the source list without view notifications. CollectionViewSource具有DeferRefresh()和Refresh()方法,使您无需更改通知即可完成更改源列表的所有后台工作。 The performance of CollectionViewSource is way better than an ObservableCollection, plus it supports filtering. CollectionViewSource的性能比ObservableCollection更好,并且它支持过滤。 Filtering might be what you need if you are constantly adding and removing items. 如果您要不断添加和删除项目,则可能需要过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM