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);
 }
相关推荐
枫叶丹415 小时前
MCP、A2A、AG-UI:一篇讲清 Agent 协议栈
人工智能·ui·chatgpt·agent·codex
李高钢16 小时前
【WPF】MVVM 与数据绑定实战:从原理到完整项目
wpf
李高钢1 天前
【WPF】从 Avalon 到 .NET 10:WPF 平台演进史与特性全览
.net·wpf
山川志~1 天前
Vue + Element UI 实战:如何实现表格时间、金额字段排序
vue.js·ui·elementui
Oll Correct1 天前
Adobe illustrator 案例六:手枪图标绘制
笔记·ui·adobe·illustrator
李高钢2 天前
WPF MVVM Light 入门:从零到Hello World
c#·wpf
李高钢2 天前
WPF MVVM Light(三):RelayCommand 命令与 Messenger 消息
前端·c#·wpf
l1m0_2 天前
React+Tailwind+AI 实战:连锁餐饮管理后台从零到一开发复盘
前端·react.js·ui·ai·ai设计
ryanuo72 天前
Shadcn/ui × Qt 6/QML:一次从 Web UI 到桌面 UI 的组件化实践
c++·qt·ui·shadcn
盛夏绽放3 天前
Proxy与Reflect详解(二):进阶篇——手写Vue3响应式系统
ui·vue3·proxy