避免WPF自定义控件中的频繁更新 [英] Avoid frequent updates in WPF custom control

查看:440
本文介绍了避免WPF自定义控件中的频繁更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在WPF中编写自定义控件.控件具有几个导致控件逻辑树更新的属性.这种形式有几种方法:

I am writing a custom control in WPF. The control have several properties that cause update of the control's logical tree. There are several methods of this form:

private static void OnXXXPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    ((MyControl)obj).RebuildTree();
}

假设RebuildTree()方法非常复杂且冗长,并且如果用户更改了多个属性,则多次调用此方法会导致应用程序变慢并挂起.

Suppose the RebuildTree() method is very complex and lenghty and if users changes several properties, this method is called several times causing application slowdown and hanging.

我想以Windows窗体的方式引入类似BeginUpdate()EndUpdate()的方法(以确保更新仅被调用一次),但是这种做法在WPF中被广泛使用.

I would like to introduce something like BeginUpdate() and EndUpdate() methods in a Windows Forms fashion (to ensure the update is called just once), but this practice is widely disouraged in WPF.

我知道渲染器的优先级较低,并且可能不会出现闪烁,但是为什么还要通过多次调用同一更新方法来浪费宝贵的运行时间呢?

I know the renderer have lower priority and flicker may not appear, but still why to spoil precious running time by calling the same update method multiple times?

是否有关于如何有效更新多个依赖项属性(在设置每个依赖项后不更新整个控件)的官方最佳实践?

推荐答案

只要这些属性中的任何一个发生更改,就设置一个标志,并使刷新方法仅在Dispatcher中排队一次.

Just set a flag when any of these properties change, and have the refresh method queued to the Dispatcher only once.

private static void OnXXXPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    ((MyControl)obj).NeedsRefresh = true;
    ((MyControl)obj).OnNeedsRefresh();
}

void OnNeedsRefresh()
{
   Dispatcher.BeginInvoke((Action)(() => 
  {
     if (NeedsRefresh)
     {
        NeedsRefresh = false;
        RebuildTree();
     }
  }),DispatcherPriority.ContextIdle);
}

这样,您的所有属性将被更新,然后分派器将调用您的BeginInvoke,将标志设置为false,并且仅刷新一次.

This way, all your properties will be updated and THEN the Dispatcher will call your BeginInvoke, set the flag to false and refresh only once.

这篇关于避免WPF自定义控件中的频繁更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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