LoginSignup
0
2

More than 5 years have passed since last update.

Visual Studio / WPF > イベント > Timer処理を使った時刻表示 | new TimeSpan(0, 0, 1); | DispatcherTimer | DateTime.Now.ToLongTimeString()

Last updated at Posted at 2017-04-30
動作環境
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2

Timer機能を使った時計の表示を試した。

リンク

参考1: https://code.msdn.microsoft.com/windowsdesktop/XAMLCVB-WPF-Windows-WPF-2aab6085
参考2: WPF – タイマースレッドからWindow内のコントロールを操作 @ astel-labs.netさん
参考3: https://msdn.microsoft.com/ja-jp/library/windows/apps/windows.ui.xaml.dispatchertimer

code

MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading; // added for Timer

namespace _170501_t0702_timer
{

    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        DispatcherTimer myTimer;

        public MainWindow()
        {
            InitializeComponent();

            myTimer = new DispatcherTimer(DispatcherPriority.Normal);
            myTimer.Interval = new TimeSpan(0, 0, 1);

            // イベント 'DispatcherTimer.Tick'は+=または-=の左側にのみ使用できます
            //myTimer.Tick = new EventHandler(myTimer_Tick);
            //
            myTimer.Tick += myTimer_Tick;

            myTimer.Start();
        }

        void myTimer_Tick(object sender, EventArgs e)
        {
            T_timer.Text = DateTime.Now.ToLongTimeString();
        }
    }
}
MainWindow.xaml
<Window x:Class="_170501_t0702_timer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_170501_t0702_timer"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock Name="T_timer" FontSize="32" Text="00:00:00" />        
    </Grid>
</Window>

work.png

はまった点

myTimer.Tick = new EventHandler(myTimer_Tick);

上記で以下のエラーが出た。

イベント 'DispatcherTimer.Tick'は+=または-=の左側にのみ使用できます

そのため、以下のように変更した。

myTimer.Tick += myTimer_Tick;
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2