Waiting for XAML layout to complete

好久不见. 提交于 2019-12-13 01:18:06

问题


I am making some changes to a page (by adding/removing controls) and I want to continue with my code only when the layout is settled (all elements measured and arranged etc).

How do I do this? Is there some Task I can await on that will fire when layout is complete?

(Right now using Yields and other tricks, but they all make me feel dirty)


回答1:


You can build a Task around any event by using TaskCompletionSource<T>.

In your case, it sounds like UIElement.LayoutUpdated may be the event you want (not entirely sure about that - WPF layout details are not my strong point).

Here's an example:

public static Task LayoutUpdatedAsync(this UIElement element)
{
  var tcs = new TaskCompletionSource<object>();
  EventHandler handler = (s, e) =>
  {
    element.LayoutUpdated -= handler;
    tcs.SetCompleted(null);
  };
  element.LayoutUpdated += handler;
  return tcs.Task;
}

Then you can use this method to await the next instance of that event:

await myUiElement.LayoutUpdatedAsync();


来源:https://stackoverflow.com/questions/14111384/waiting-for-xaml-layout-to-complete

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