wpf 窗体中显示当前系统时间
先看一下效果:

这其实是我放置了两个TextBlock,上面显示当前的日期,下面显示时间。
接下来展示一下代码:
在XAML中:
<StackPanel Width="205"
                    Margin="0,0,57,0"
                    HorizontalAlignment="Right">
            <TextBlock Height="Auto"
                       Margin="10,5,0,0"
                       Name="tbDateText"
                       Foreground="White"
                       FontWeight="Bold"
                       FontFamily="Arial"
                       FontSize="15" />
            <TextBlock Height="Auto"
                       Margin="10,5,0,0"
                       Name="tbTimeText"
                       Foreground="#ffa51f"
                       FontWeight="Bold"
                       FontFamily="Calibri"
                       FontSize="23" />
        </StackPanel>
在主窗体的cs中代码为:
/// <summary>
/// 定义一个定时器
/// </summary>
private DispatcherTimer ShowTimer;
public MainWindow()
{
InitializeComponent();
ShowTime(); //在这里窗体加载的时候不执行文本框赋值,窗体上不会及时的把时间显示出来,而是等待了片刻才显示了出来
ShowTimer = new System.Windows.Threading.DispatcherTimer();
ShowTimer.Tick += new EventHandler(ShowCurTimer);//起个Timer一直获取当前时间
ShowTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
ShowTimer.Start();
}
public void ShowCurTimer(object sender, EventArgs e)
{
ShowTime();
}
//ShowTime方法
private void ShowTime() 
{
            //获得年月日
            this.tbDateText.Text = DateTime.Now.ToString("yyyy/MM/dd");   //yyyy/MM/dd
            //获得时分秒
            this.tbTimeText.Text = DateTime.Now.ToString("HH:mm:ss");
}
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号