65.9K
CodeProject 正在变化。 阅读更多。
Home

SilverLight 2 中的数字时钟

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.24/5 (8投票s)

2008 年 11 月 27 日

CPOL
viewsIcon

51611

downloadIcon

2639

如何创建一个简单的 SilverLight 2 数字时钟。

SLdigitalClock.jpg

引言

本教程展示了如何在 SilverLight 2 中创建一个简单的数字时钟。 我还在 WPFExpression Blend 2 中创建了模拟时钟。

使用代码

首先,我们需要创建一个计时器。 我从 这里 学到了如何做到这一点。

public void StartTimer(object o, RoutedEventArgs sender)
{
    System.Windows.Threading.DispatcherTimer myDispatcherTimer = 
        new System.Windows.Threading.DispatcherTimer();
    myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1000 Milliseconds
    myDispatcherTimer.Tick += new EventHandler(Each_Tick);
    myDispatcherTimer.Start();
}

现在,我们应该使用 XAML 代码创建三个 TextBlock

<TextBlock Margin="8,8,0,9" Foreground="#FFFFFFFF" 
    TextWrapping="Wrap" HorizontalAlignment="Left" 
    FontSize="72" Text="00" 
    d:LayoutOverrides="HorizontalAlignment, 
    Height" VerticalAlignment="Center" x:Name="hourText"/>

现在,我们编写一个方法来每秒更改文本

// Fires every 1000 miliseconds while the DispatcherTimer is active.
public void Each_Tick(object o, EventArgs sender)
{
    hourText.Text = DateTime.Now.Hour.ToString();
    minuteText.Text = DateTime.Now.Minute.ToString();
    secondText.Text = DateTime.Now.Second.ToString();
}

历史

  • 2008年11月27日:首次发布。
© . All rights reserved.