2011-12-23 63 views
1

我正在尝试为Windows Phone 7编程某种秒表。为了衡量经过的时间,我使用了Stopwatch类。要打印输出,我使用文本块。但我希望textblock始终显示已用时间。Windows Phone 7永久更新文本块

Unitl现在我只能更新事件上的文本块(我使用button_Click事件) 我尝试了一段时间(真)循环,但这只冻结了手机。

有没有人有关我如何解决这个问题的好主意?

回答

2

StopWatch类没有任何事件,因此如果要绑定,则必须编写自己的类或使用计时器轮询StopWatch。 您可以使用绑定将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(); 
+0

感谢您快速的解答。我正在寻找像绑定但没有找到的东西。不幸的是它不起作用(我认为它应该)我想使用一个变量String show = randomTimespanvariable.ToString(); – asky 2011-12-23 17:12:25

+0

绑定不起作用的原因非常简单。 Stopwatch.Elapsed不是DependancyProperty。原因不是因为你不想每1毫秒更新它的值。你的情况没有优雅的绑定解决方案。我尝试了上面的代码,即使使用'Timespan.FromSeconds(0.1)'作为Interval,它的工作也非常好。 – 2011-12-23 17:14:17

+0

如果你仍然想要绑定,只需将myStopWatch.Elapsed值分配给字符串类型的DependancyPeoprty,然后只是将TextBlock绑定到该绑定,但在功能上您没有更改任何内容,也许不需要调用Dispatcher。让我知道你是否需要代码帮助。 – 2011-12-23 17:20:27