WPF 一个执行耗时任务,页面更新等待时间的例子

xaml页面,一个按钮,一个lable,lable用来更新等待的时间。点击按钮,每过1秒,label的数值+1,直到任务结束。

XML 复制代码
<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="350,0,0,0" VerticalAlignment="Center" Height="72" Width="149" Click="Button_Click"/>
        <Label Content="0" HorizontalAlignment="Left" Margin="350,281,0,0" VerticalAlignment="Top"  x:Name="Lab"/>

    </Grid>
</Window>

.cs代码

cs 复制代码
 private async void Button_Click(object sender, RoutedEventArgs e)
 {
     bool isOk = false;
     Wait((result)=>isOk = result);
     while (!isOk)
     {
         //等待耗时任务结束,界面的Label加1
         await Task.Delay(1000);
         Lab.Content = Convert.ToInt32(Lab.Content) + 1;
     }
 }

 private async void Wait(Action<bool> callback)
 {
     bool isok = false;
     //耗时任务
     for (int i = 0; i < 10; i++)
     {
         await Task.Delay(1000);
     }
     isok = true;
     callback?.Invoke(isok);
 }
相关推荐
qq_4523962313 小时前
第一篇:《UI自动化测试从零到一:为什么需要它?核心价值与挑战》
ui
SEO-狼术1 天前
Easily Reorder Rows in WPF Grids
wpf
深蓝海拓1 天前
基于QtPy (PySide6) 的PLC-HMI工程项目(十一)框架的进一步完善:UI的自动周期更新以及下行数据的生成和处理
网络·笔记·python·学习·ui·plc
qq_452396231 天前
第二篇:《主流UI自动化工具横向对比:Selenium、Cypress、Playwright、Puppeteer》
selenium·ui·自动化
hzxpaipai1 天前
[UI/UX 实战] 长页面交互优化:如何通过常驻侧边导航解决用户“浏览迷失”?
ui·ux
QC·Rex2 天前
Spring AI MCP Apps 实战:打造聊天与富 UI 融合的智能化应用
人工智能·spring·ui·spring ai·mcp
ai_coder_ai2 天前
自动化脚本ui编程之帧布局(frame)
ui·autojs·自动化脚本·冰狐智能辅助·easyclick
天天进步20152 天前
不止于 UI:OpenWork 的核心哲学与“引擎+外壳”架构全景图
人工智能·ui·架构
星辰即远方2 天前
UI学习3
学习·ui
比老马还六2 天前
element-ui,使用el-table时,type=“expand“和fixed一起使用坑
开发语言·javascript·ui