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

前端 未结 1 1356
误落风尘
误落风尘 2021-01-18 00:09

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 dispat

1条回答
  •  盖世英雄少女心
    2021-01-18 01:07

    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.

    0 讨论(0)
提交回复
热议问题