Waiting for XAML layout to complete

2019-08-08 02:34发布

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条回答
老娘就宠你
2楼-- · 2019-08-08 02:54

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();
查看更多
登录 后发表回答