问题
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