この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();