最近做一个WPF小项目需要使用到计时器,因此写了一个计时控件,记录下来,以便下次使用。
前台的XAML:
<UserControlx:Class="Test.CountDown"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"mc:Ignorable="d"d:DesignHeight="110"d:DesignWidth="150"><Grid><Grid.ColumnDefinitions><ColumnDefinitionWidth="43*"/><ColumnDefinitionWidth="13"/><ColumnDefinitionWidth="43*"/><ColumnDefinitionWidth="13"/><ColumnDefinitionWidth="43*"/></Grid.ColumnDefinitions><TextBlockText="00"Name="HourArea"VerticalAlignment="Center"FontSize="30"Background="Transparent"Grid.Column="0"Foreground="DarkOrange"/><TextBlockText=":"Name="HourSplitMinute"VerticalAlignment="Center"FontSize="30"Background="Transparent"Grid.Column="1"Foreground="DarkOrange"/><TextBlockText="00"Name="MinuteArea"VerticalAlignment="Center"FontSize="30"Background="Transparent"Grid.Column="2"Foreground="DarkOrange"/><TextBlockText=":"Name="MinuteSplitSecond"VerticalAlignment="Center"FontSize="30"Background="Transparent"Grid.Column="3"Foreground="DarkOrange"/><TextBlockText="00"Name="SecondArea"VerticalAlignment="Center"FontSize="30"Background="Transparent"Grid.Column="4"Foreground="DarkOrange"/></Grid></UserControl>
View Code
后台的逻辑:
publicpartialclassCountDown : UserControl
{publicDispatcherTimer timer;publicProcess pro;publicStopwatch sw =newStopwatch();publicintseconds;publicCountDown()
{
InitializeComponent();
pro=newProcess();
timer=newDispatcherTimer();
timer.Interval=newTimeSpan(0,0,1);
timer.Tick+=newEventHandler(timer_Tick);
}voidtimer_Tick(objectsender, EventArgs e)
{
TimeSpan ts=newTimeSpan (0,0,seconds);
pro.totalSecond= (int)(ts -sw.Elapsed).TotalSeconds;if(pro .totalSecond >0)
{
HourArea.Text=pro.GetHour();
MinuteArea.Text=pro.GetMinute();
SecondArea.Text=pro.GetSecond();
}else{
timer.Stop();
sw.Stop ();
sw.Reset();
SecondArea.Text=string.Format("{0:D2}",0);
}
}
}publicclassProcess
{publicinttotalSecond;//获取小时字符串publicstringGetHour()
{returnstring.Format("{0:D2}", totalSecond /3600);
}//获取分钟字符串publicstringGetMinute()
{returnstring.Format("{0:D2}", (totalSecond /60- ((int)(totalSecond /3600) *60)));
}//获取秒字符串publicstringGetSecond()
{returnstring.Format("{0:D2}", totalSecond %60);
}
}
View Code
调用:
this.countDown1.timer.Stop();
this.countDown1.sw.Reset();
this.countDown1.seconds = 300;//传入倒计时总时间(秒)
this.countDown1.timer.Start();
this.countDown1.sw.Start();
2014。11.28日补充:
最近一个小项目需要用到服务器的系统时间,而且需要精确到小数点后三位。方法如下:
publicDateTime GetTime()
{stringstrSql ="select getdate()";
DateTime dt;
SqlDataReader dataReader=DbHelperSQL.ExecuteReader(strSql);if(dataReader.Read())
{
dt= (DateTime)dataReader[0];
dataReader.Close();returndt;
}returnDateTime.MinValue;
}