DispatcherTimer 를 이용해 시계를 만들어보도록 한다.
먼저 using으로 using System.Windows.Threading; Namespace를 추가해야 하고 다음을 따라 진행한다
-
Xaml
<UserControl x:Class="ClockSample.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock FontSize="60" TextAlignment="Center" VerticalAlignment="Center" x:Name="tbTime" Text="12:00:00" />
</Grid>
</UserControl>
- Code
public Page()
{
InitializeComponent();
TimerSetting();
}
private void TimerSetting()
{
DispatcherTimer timer = new DispatcherTimer()
{
Interval = TimeSpan.FromMilliseconds(50)
};
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
this.tbTime.Text = DateTime.Now.ToString("HH:mm:ss");
}
-
다음과 같이 시계가 잘 작동한다.