17

結果をhh:mm:ssとしてテキストボックスに表示するwpfカウントダウンタイマーを作成したいのですが、誰の助けにも感謝します。

4

2 に答える 2

32

DispatcherTimerクラス ( msdn )を使用できます。

TimeSpan構造体 ( msdn )に保持できる期間。

TimeSpanフォーマットしたい場合は、「c」引数(msdnhh:mm:ss )でメソッドを呼び出す必要があります。ToString

例:

XAML:

<Window x:Class="CountdownTimer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock Name="tbTime" />
    </Grid>
</Window>

分離コード:

using System;
using System.Windows;
using System.Windows.Threading;

namespace CountdownTimer
{
    public partial class MainWindow : Window
    {
        DispatcherTimer _timer;
        TimeSpan _time;

        public MainWindow()
        {
            InitializeComponent();

            _time = TimeSpan.FromSeconds(10);

            _timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
                {
                    tbTime.Text = _time.ToString("c");
                    if (_time == TimeSpan.Zero) _timer.Stop();
                    _time = _time.Add(TimeSpan.FromSeconds(-1));                    
                }, Application.Current.Dispatcher);

            _timer.Start();            
        }
    }
}
于 2013-05-25T12:14:33.633 に答える