1

Windows Phone 7 用のある種のストップウォッチをプログラムしようとしています。経過時間を測定するには、Stopwatch クラスを使用します。出力を印刷するには、テキストブロックを使用します。しかし、テキストブロックに経過時間を常に表示したいと思います。

Unitl では、イベントでのみテキストブロックを更新できます (button_Click イベントを使用します) while(true) ループを試しましたが、電話がフリーズするだけです。

これを修正する方法について誰かが良い考えを持っていますか?

4

1 に答える 1

2

このStopWatchクラスにはイベントがないため、バインドする場合は、独自のクラスを作成するか、タイマーで StopWatch をポーリングする必要があります。Binding を使用して、TextBlock からストップウォッチにプロパティをバインドできます。まず、この DataContext バインディングをページの xaml に追加します。

 <phone:PhoneApplicationPage
      DataContext="{Binding RelativeSource={RelativeSource Self}}" >

次に、テキストブロックを次のようにバインドします

 <TextBlock x:Name="myTextBlock" Text="{Binding StopwatchTime}" />

コード ビハインドで、DependancyProperty と必要なタイマー コードを追加します。

    public static readonly DependencyProperty StopwatchTimeProperty =
        DependencyProperty.Register("StopwatchTime", typeof(string), typeof(MainPage), new PropertyMetadata(string.Empty));

    public string StopwatchTime
    {
        get { return (string)GetValue(StopwatchTimeProperty); }
        set { SetValue(StopwatchTimeProperty, value); }
    }

そしてタイマーコードはどこかに...

        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(0.2); // customize update interval
        timer.Tick += delegate(object sender, EventArgs e)
        {
            StopwatchTime = sw.Elapsed.Seconds.ToString(); // customize format
        };
        timer.Start();
于 2011-12-23T02:59:18.047 に答える