UI更新频率与绑定 [英] UI update frequency with bindings

查看:80
本文介绍了UI更新频率与绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的视图中,我有一个图表,其中包含一系列绑定到ViewModel中公开的 ObservableCollection 。 ViewModel中有一个计算密集型的方法,该方法更新了系列绑定的 ObservableCollection 中的值。该方法需要很长时间才能完成,因此我从一个单独的线程启动它。



该方法需要很长时间才能完成,但是正在更改 ObservableCollection 非常快速而频繁。因此,我在UI中遇到了类似于在UI线程上运行该方法的延迟。



有没有办法限制UI在绑定中的元素发生变化时尝试更新图表的频率?或者是ViewModel的工作是要注意这个潜在的问题并间歇地执行对 ObservableCollection 的更改 - 比如使用一个计时器来检查以确保至少已经过了150ms因为 ObservableCollection 中的元素已更新?

解决方案

最好的方法是维护一个字典自刷新以来已被戳过的对象,而不是引发PropertyChanged事件,如果该条目不存在,则添加到该字典...



然后创建附加的行为到具有ItemsSource {Binding< myobservablecollection>}的Items控件。



在此行为中,创建一个调度程序计时器,并在勾选时循环遍历字典,并提升这些对象的属性。然后从字典中删除条目。



如果您使用的是WPF,我建议使用ConcurrentDictionary< whateverworksasakey,weakreference>< myviewmodel>>



否则你将不得不围绕包含/添加/删除逻辑锁定一个锁,在你的情况下,它可能不是一个好主意,因为它的频率很高。

In my View I have a chart which has a series that is bound to an ObservableCollection that is exposed in the ViewModel. There is a method in the ViewModel which is very computationally intensive and that method updates the values within the ObservableCollection that the series is bound to. The method takes a long time to complete so I launch it from a separate thread.

The method takes a long time to complete but is changing the parameters of the objects in the ObservableCollection very quickly and frequently. Because of this I am experiencing a lag in the UI similar to as if I was running the method on the UI thread.

Is there a way to limit how frequently the UI attempts to update the chart whenever an element within the binding gets changed? Or is it the job of the ViewModel to be aware of this potential problem and execute changes to the ObservableCollection intermittently - say with a timer which checks to make sure at least 150ms has passed since an element within the ObservableCollection has been updated?

解决方案

The best way would be to maintain a Dictionary of objects that have been poked since refresh, and rather than raising a PropertyChanged event, add to that dictionary if the entry does not exist...

Then create a behavior attached to the Items control that has the ItemsSource {Binding <myobservablecollection>}.

In this behavior, create a dispatcher timer, and on tick, loop through the Dictionary, and raise property changed on those objects. Then remove the entry from the dictionary.

If you are on WPF I would recommend that the dictionary uses ConcurrentDictionary<whateverworksasakey,weakreference><myviewmodel>>

Else you are going to have to wrap a lock around the contains/add/remove logic, which in your case might not be a good idea as its high frequency.


这篇关于UI更新频率与绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆