Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF how to wait for binding update to occur before processing more code?

Tags:

c#

wpf

xaml

As I understand it the dispatcher takes place in another thread, which takes care of updating data bindings, layout, etc. However, is there any way to wait until the dispatcher has no more items or at least no more data bindings? I want to ensure that the property change has updated all of its components and run the dependent property changed callbacks before running more code.

edit: so I am guessing that this is not needed, I am just trying to understand what I should have done instead. My main question is at WPF if the children of a scrollviewer resize, will the scrollviewer automatically update its extent?

but I was also curious whether i could wait for bindings to update or if there is even any guarantee that one binding updates before another? Am I expected to code such that the order of binding updates do not matter? currently I used dependency property changed callback's that perform various stuff that is often dependent on other properties updating

like image 436
James Joshua Street Avatar asked Aug 23 '13 19:08

James Joshua Street


1 Answers

The dispatcher has several priorities for processing the single tasks. I'm quite sure you cannot change the priority of the callbacks of dependency properties. If they were changed by data binding, they will be in queue with DispatcherPriority.DataBinding priority. You manipulate the values of some dependency properties which would cause layout/other dependency properties to change. And you want to wait after your first manipulation until these layout updates/changes are processed and then do something with the current UI state?

WinForms had the DoEvents function for such cases which causes all UI events being processed before normal code execution continues. WPF has no such builtin function but you can write your own DoEvents:

public static void DoEvents()
{
  if (Application.Current == null)
    return;
  Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, (Delegate) (() => {}));
}

The empty delegate is invoked synchronously, that means the call returns after the delegate was executed by the dispatcher. The DispatcherPriority.Background is a very low priority so that this dispatcher call is processed after for example data bindings, layout updates or rendering. http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherpriority.aspx

So call DoEvents() after your first manipulation of the dependency properties and before you want to read other dependency properties and it should be done.

like image 98
Torben Schramme Avatar answered Oct 05 '22 20:10

Torben Schramme