簡體   English   中英

如何在WPF中獲取數字以在屏幕上向前計數?

[英]How can I get a number to count forward on the screen in WPF?

我要做的就是向我5歲的女兒展示如何在屏幕上計算數字

這將等待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);
            }
        }
    }
}

對於這樣的快速項目,可以使用計時器:

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();
}

如果您希望在任務運行時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";
    }
}

您可以在此處了解更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM