2009-12-16 21 views
0

我想要做的就是向我的5歲女兒展示號碼如何在屏幕上計數如何在WPF屏幕上獲得一個數字以進行計數?

這等待135秒,然後顯示「135」。

我必須改變什麼才能顯示數字?

XAML:

<Window x:Class="TestCount234.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="768" Width="1024"> 
    <StackPanel> 
     <TextBlock 
      HorizontalAlignment="Center" 
      FontSize="444" x:Name="TheNumber"/> 
    </StackPanel> 
</Window> 

代碼背後:

using System.Windows; 
using System.Threading; 

namespace TestCount234 
{ 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 
      Loaded += new RoutedEventHandler(Window1_Loaded); 
     } 

     void Window1_Loaded(object sender, RoutedEventArgs e) 
     { 
      for (int i = 0; i <= 135; i++) 
      { 
       TheNumber.Text = i.ToString(); 
       Thread.Sleep(1000); 
      } 
     } 
    } 
} 

回答

3

對於這樣一個匆匆的項目,你可以使用一個計時器:

private DispatcherTimer timer; 
private int count = 0; 

public Window1() 
{ 
    InitializeComponent(); 
    this.timer = new DispatcherTimer(); 
    this.timer.Interval = TimeSpan.FromSeconds(1); 
    this.timer.Tick += new EventHandler(timer_Tick); 
    this.timer.Start(); 
} 

void timer_Tick(object sender, EventArgs e) 
{ 
    this.textBox1.Text = (++count).ToString(); 
} 
+0

謝謝,這樣的作品,並在5歲的關注範圍,謝謝! – 2009-12-16 18:59:28

2

如果你想在UI更新(並保持響應)你的任務運行時,您需要使用一個單獨的線程,例如通過使用BackgroundWorker

這裏是它如何工作的例子:

BackgroundWorker _backgroundWorker = new BackgroundWorker(); 

... 

// Set up the Background Worker Events 
_backgroundWorker.DoWork += _backgroundWorker_DoWork; 
backgroundWorker.RunWorkerCompleted += 
    _backgroundWorker_RunWorkerCompleted; 

// Run the Background Worker 
_backgroundWorker.RunWorkerAsync(5000); 

... 

// Worker Method 
void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e) 
{ 
    // Do something 
} 

// Completed Method 
void _backgroundWorker_RunWorkerCompleted(
    object sender, 
    RunWorkerCompletedEventArgs e) 
{ 
    if (e.Cancelled) 
    { 
     statusText.Text = "Cancelled"; 
    } 
    else if (e.Error != null) 
    { 
     statusText.Text = "Exception Thrown"; 
    } 
    else 
    { 
     statusText.Text = "Completed"; 
    } 
} 

You can read a lot more about it here.

相關問題