.NET

#ref(): File not found: "wpfclock1.png" at page "wpf、タイマーからオブジェクトに書き込み"

「そんなん簡単じゃん、 timerをフォームからドラッグして……
 待ちなさいシ○ウ、それは Windows Form のタイマーなの。wpfでは当然使えないし、使えても使うべきではないのよ。
 でも、だからといって System.timers.timer もダメ。あれはとても正確だけど、別スレッドにいる wpf オブジェクトにアクセスできないからね。
 厳密にはアクセス不可能じゃないけど、ここ見てるようなレベルの人が使うものではないと思うの。

 こんな時には、 DispatcherTimer を使いましょうね。

using System.Windows.Threading;

namespace clock1
{

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

       DispatcherTimer dispatcherTimer;
       string tt1 = "";

       public MainWindow()
       {
           InitializeComponent();

           dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal);
           dispatcherTimer.Interval = new TimeSpan(0,0,0,0,100);
           dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
           dispatcherTimer.Start();

           setClock();
       }

       void dispatcherTimer_Tick(object sender, EventArgs e)
       {
           setClock();
       }

       public void setClock()
       {
           string tt2 = DateTime.Now.ToLongTimeString();
           if (tt1 != tt2)
           {
               tt1 = tt2;
               t1.Text = tt1;
           }
       }

   }
}

トップ   編集 凍結解除 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2016-02-14 (日) 19:39:18