WPF中添加个简单的显示当前系统时间的示例

东西很简单,不过以前没见过的话,如果让人直接去实现,还得查查资料,用的东西很少

建一个WPF工程,当然silverlight也行,放置一个 TextBlock 在面板上

代码:

<Grid x:Name="LayoutRoot">
<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="1"/>
<GradientStop Color="#FF00D1FF"/>
</LinearGradientBrush>
</Grid.Background>
<TextBlock x:Name="Tt" FontSize="30" Margin="8,43,8,68" TextWrapping="Wrap">
<TextBlock.Foreground>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FFEE580F" Offset="1"/>
</LinearGradientBrush>
</TextBlock.Foreground>
</TextBlock>
</Grid>

下面就是后台C#里的东西啦,也没什么东西,首先要为显示当前系统时间起一个Timer。直接代码:

namespace 显示当前系统时间
{
	/// <summary>
	/// MainWindow.xaml 的交互逻辑
	/// </summary>
	public partial class MainWindow : Window
	{
		
		private DispatcherTimer ShowTimer;
		public MainWindow()
		{
			this.InitializeComponent();

			// 在此点下面插入创建对象所需的代码。
			//show timer by_songgp
			ShowTimer = new System.Windows.Threading.DispatcherTimer();
        	ShowTimer.Tick += new EventHandler(ShowCurTimer);//起个Timer一直获取当前时间
        	ShowTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
        	ShowTimer.Start();
		
		}
		
		//show timer by_songgp
		 public void ShowCurTimer(object sender, EventArgs e)
        {
            //"星期"+DateTime.Now.DayOfWeek.ToString(("d"))
			
			//获得星期几
            this.Tt.Text =  DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("zh-cn"));
            this.Tt.Text += " ";
			//获得年月日
            this.Tt.Text += DateTime.Now.ToString("yyyy年MM月dd日");   //yyyy年MM月dd日
            this.Tt.Text += " ";
			//获得时分秒
            this.Tt.Text += DateTime.Now.ToString("HH:mm:ss:ms");
            //System.Diagnostics.Debug.Print("this.ShowCurrentTime {0}", this.ShowCurrentTime);
        }
	}
}

这里记得要加一个头文件:using System.Windows.Threading;

搞定,运行一下看下效果吧。

预览图:

呼呼~~~

原文地址:https://www.cnblogs.com/wainiwann/p/WPF_silverlight_Timer_TextBlock.html