![](/img/trans.png)
[英]Set UI element visible in Xamarin C# and then call asynchronous function
[英]Function runs before UI gets changed to visible even though the UI was set to visible before the function was ran
基本上我有一个 C# WinUI3 应用程序,它有一个运行进程的功能,我希望它使一些文本标签可见以向用户显示应用程序正在做什么,但是即使我将可见性设置为可见,它也不会在所有功能完成运行并且按钮保持单击状态并且看起来应用程序挂起之前,它不会被更改,即使它没有挂起。 这是我的代码的照片。
我不知道从哪里开始解决这个问题,我已经查看了我的问题,但到目前为止似乎还没有找到任何答案。 抱歉,如果我在帖子中做错了什么,我对堆栈溢出还很陌生
您的 UI 没有更新,因为您正在 UI 线程中运行所有内容。 我想您需要了解async / await 。 这是 Stephen Cleary 的一个很好的教程。
试试这段代码,您会看到 UI 得到了更新。
<Button
Click="Button_Click"
Content="Start" />
<TextBlock
x:Name="MessageTextBlock"
Text="Click the button." />
private async void Button_Click(object sender, RoutedEventArgs e)
{
// Starts running on the UI thread.
MessageTextBlock.Text = "Running process...";
await RunProcess();
MessageTextBlock.Text = "Done!";
}
private async Task RunProcess()
{
// Releases the thread that called this method,
// the UI thread in this case,
// and lets "another thread" to run this "heavy work".
// This is why the UI thread can update the MessageTextBlock
// while "another thread" is doing the "heavy work".
await Task.Run(async () =>
{
// heavy work.
await Task.Delay(1000);
});
// Brings back the UI thread.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.