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);
 }
相关推荐
小海聊工控上位机4 小时前
WPF自定义模板--TreeView 实现菜单连接线
wpf
东方佑5 小时前
使用tkinter 制作工作流ui
前端·windows·笔记·python·ui·分类
普罗米修斯Aaron_Swartz6 小时前
WPF更新UI线程实现进度条功能
ui·wpf
lyx49491 天前
在TkinterGUI界面显示WIFI网络摄像头(ESP32s3)视频画面
opencv·ui·计算机视觉
是Yu欸1 天前
【前端实现】在父组件中调用公共子组件:注意事项&逻辑示例 + 将后端数组数据格式转换为前端对象数组形式 + 增加和删除行
前端·vue.js·笔记·ui·vue
界面开发小八哥1 天前
DevExpress WPF中文教程:Grid - 如何显示摘要(设计时)?
ui·c#·wpf·界面控件·devexpress
Dnelic-1 天前
Android 15 应用适配默认全屏的行为变更(Android V的新特性)
android·ui·view·应用开发·android 15·android应用开发
jackfb20122 天前
命令可以不通过数据绑定进行配置
wpf
code_shenbing2 天前
上位机网络通讯
前端·数据库·ui·c#·winform