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");
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM