WPF中的时间实现

WPF中的时间实现

开发工具与关键技术:Visual Studio 2015、WPF
作者:黄元进
撰写时间:2019年4月23日

这里我先用TextBlock (文本)来操作,把它水平垂直居中。
使用XAML代码实现如下:

<Window x:Class="Wpf的时间代码.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        WindowStartupLocation="CenterScreen"
        Title="MainWindow" Height="200" Width="300">
    <Grid>
        <TextBlock x:Name="sj" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Grid>
</Window>

然后就是使用C#代码实现,一些意思在后面已备注

using System;
using System.Windows;
using System.Windows.Threading;

namespace Wpf的时间代码
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        #region 全局变量
        //声明计时器
        private DispatcherTimer showtimer;//自定义名称showtimer
        #endregion
        public MainWindow()
        {
            InitializeComponent();
            #region 显示时间
            showtimer = new DispatcherTimer();//实例化
            showtimer.Tick += new EventHandler(ShowCurTimer);
            showtimer.Interval = new TimeSpan(0, 0, 0, 1, 0);//控制时间在一秒钟跳动一次
            showtimer.Start();//开启时间
            #endregion
        }
        //定义一个方法
        public void ShowCurTimer(object sender, EventArgs e)
        {
            sj.Text = DateTime.Now.ToString("yyyy'年-'MM'月'-dd'日' HH:mm:ss");//确定时间格式
        }
    }
}

实现效果图:
在这里插入图片描述
提示:后面的秒数是可以跳动的,由于截图就看不了,可以复制代码到VS来查看效果

猜你喜欢

转载自blog.csdn.net/weixin_44547949/article/details/89565102