等待XAML布局完成 [英] Waiting for XAML layout to complete
问题描述
我正在对页面进行一些更改(通过添加/删除控件),并且仅在布局确定(所有元素都已测量和排列等)之后,我才继续执行我的代码.
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?
(现在使用Yields和其他技巧,但它们都使我感到肮脏)
(Right now using Yields and other tricks, but they all make me feel dirty)
推荐答案
您可以使用 TaskCompletionSource< T>
围绕任何事件构建 Task
.
You can build a Task
around any event by using TaskCompletionSource<T>
.
在您的情况下,听起来像 UIElement.LayoutUpdated
可能是您想要的事件(对此不完全确定-WPF布局细节不是我的强项).
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).
这是一个例子:
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();
这篇关于等待XAML布局完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!