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);
 }
相关推荐
hudawei99620 小时前
TweenAnimationBuilder和AnimatedBuilder两种动画的比较
flutter·ui·动画·tweenanimation·animatedbuilder
依米阳光081 天前
Playwright MCP AI实现自动化UI测试
ui·自动化·playwright·mcp
芷栀夏1 天前
CANN 仓库实战:用 DrissionPage 构建高效、稳定的 UI 自动化测试框架
ui·aigc·transformer·cann
User_芊芊君子1 天前
【分布式训练】CANN SHMEM跨设备内存通信库:构建高效多机多卡训练的关键组件
分布式·深度学习·神经网络·wpf
微祎_1 天前
构建一个 Flutter 点击速度测试器:深入解析实时交互、性能度量与响应式 UI 设计
flutter·ui·交互
AAA阿giao1 天前
从零拆解一个 React + TypeScript 的 TodoList:模块化、数据流与工程实践
前端·react.js·ui·typescript·前端框架
晚霞的不甘1 天前
Flutter for OpenHarmony 构建简洁高效的待办事项应用 实战解析
flutter·ui·前端框架·交互·鸿蒙
百思可瑞教育1 天前
构建自己的Vue UI组件库:从设计到发布
前端·javascript·vue.js·ui·百思可瑞教育·北京百思教育
XPii2 天前
Photoshop应用——将图片变为水墨画效果
ui·photoshop
AC梦2 天前
unity中如何将UI上的字高清显示
ui·unity