c# WPF 实现倒计时功能中遇到的一些问题
前言
您好,感谢您可以打开本贴,希望您可以花费一点时间阅读一下我的代码,帮我解决一下问题,感激不尽!
这是一个按我自己的想法实现的倒计时功能,可能不太成熟,望见谅
问题描述
我是使用的for循环实现的倒计时,开启就无响应,但是for循环内的第一句加上一个弹窗就不会了,想请问一下为什么以及解决方案,感激不尽!
代码展示
Concentration.xaml
<UserControl x:Class="NiceToDo_of_zzcy_for_windows_by_csharp.Concentration"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:NiceToDo_of_zzcy_for_windows_by_csharp"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<TextBox x:Name="ConcentrationTextBox" HorizontalAlignment="Left" Margin="225,0,0,0" TextWrapping="Wrap" Text="加载中..." VerticalAlignment="Center" Width="350" Height="50" FontSize="30" FontWeight="Bold" TextAlignment="Center" IsReadOnly="True"/>
<Button Content="开始" HorizontalAlignment="Left" Margin="225,293,0,0" VerticalAlignment="Top" Width="100" Click="Start"/>
<Button Content="暂停" HorizontalAlignment="Left" Margin="350,293,0,0" Width="100" Height="32" VerticalAlignment="Top" Click="Suspend"/>
<Button Content="结束" HorizontalAlignment="Left" Margin="475,293,0,0" VerticalAlignment="Top" Width="100" Click="Stop"/>
</Grid>
</UserControl>
Concentration.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace NiceToDo_of_zzcy_for_windows_by_csharp
{
///
/// Concentration.xaml 的交互逻辑
///
public partial class Concentration : UserControl
{
private string sh = "", sm = "", ss = "";
private long h, m, s, ls;
public Concentration(long h,long m,long s,long ls)//h是小时m是分钟s是秒ls是总秒数,这些值在构造的时候都会传入
{
InitializeComponent();
this.h = h;
this.m = m;
this.s = s;
this.ls = ls;
ShowTime();
}
private void ShowTime()
{
if (h < 10)
{
sh = "0" + h.ToString();
}
else
{
sh = h.ToString();
}
if (m < 10)
{
sm = "0" + m.ToString();
}
else
{
sm = m.ToString();
}
if (s < 10)
{
ss = "0" + s.ToString();
}
else
{
ss = s.ToString();
}
ConcentrationTextBox.Text = sh + ":" + sm + ":" + ss;
}
private void Start(object sender, RoutedEventArgs e)
{
MessageBox.Show("start");
for (long i = 0; ls >= 0; ls--, i++)
{
MessageBox.Show("for "+i+"ls "+ls);//问题就在这!
if (s == 0)
{
if (m > 0)
{
m--;
s = 60;
}
}
if (m == 0)
{
if (h > 0)
{
h--;
m = 60;
}
}
ShowTime();
Thread.Sleep(1000);
s--;
}
MessageBox.Show("倒计时已结束");
}
private void Suspend(object sender, RoutedEventArgs e)
{
}
private void Stop(object sender, RoutedEventArgs e)
{
}
}
}