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