Avoid frequent updates in WPF custom control

白昼怎懂夜的黑 提交于 2019-12-13 04:42:20

问题


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();
}

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.

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?

Is there any official best practice on how to make efficient update of multiple dependency properties (without updating the entire control after setting each one)?


回答1:


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);
}

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.



来源:https://stackoverflow.com/questions/17818394/avoid-frequent-updates-in-wpf-custom-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!