XAML 函数在UI更改为可见之前运行,即使UI在函数运行之前已设置为可见

voj3qocg  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(86)

基本上,我有一个C# WinUI3应用程序,它有一个运行进程的函数,我希望它使一些文本标签可见,以向用户显示应用程序正在做什么,然而,即使我将可见性设置为可见,它也不会改变,直到所有函数都完成运行,按钮只是停留在点击状态,看起来好像应用程序挂起,即使它没有。Here's a photo of my code.
我不知道从哪里开始解决这个问题,我已经查找了我的问题,似乎还没有找到任何答案。对不起,如果我在我的帖子中做错了什么,我是相当新的堆栈溢出😅

sf6xfgos

sf6xfgos1#

你的UI没有更新,因为你正在UI线程中运行所有的东西。我猜你需要学习async/awaitHere是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" 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.
}

相关问题