我正在尝试为 Windows Phone 7 编写某种秒表。为了测量经过的时间,我使用了 Stopwatch 类。要打印输出,我使用文本块。但我希望文本块一直显示经过的时间。
Unitl 现在我只能更新事件的文本块(我使用 button_Click 事件)我尝试了一个 while(true) 循环,但这只会冻结手机。
有没有人知道如何解决这个问题?
我正在尝试为 Windows Phone 7 编写某种秒表。为了测量经过的时间,我使用了 Stopwatch 类。要打印输出,我使用文本块。但我希望文本块一直显示经过的时间。
Unitl 现在我只能更新事件的文本块(我使用 button_Click 事件)我尝试了一个 while(true) 循环,但这只会冻结手机。
有没有人知道如何解决这个问题?
该类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();