为什么我看不到MainPage中TextBlock文本的每个更改? [英] Why do I not see each change to a TextBlock text in the MainPage ?

查看:68
本文介绍了为什么我看不到MainPage中TextBlock文本的每个更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我这样做,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace MVVMCounter
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            output.Text = "test";
            System.Threading.Thread.Sleep(5000);
            output.Text = "next";
        }
    }
}

为什么我只看到文本块文本的最后一个变形? (输出是XAML上的TextBlock,x:Name =" output")

Why do I only see the very last chenge to the text block text? (output is a TextBlock on the XAML with x:Name = "output")

不确定为什么,但我希望页面加载,文本首先显示为"test"然后改为"下一个"后  5秒。

Not sure why but I expected the page to load and the text to first appear as "test" and then change to "next" after  5 seconds.

推荐答案

您的MainPage构造函数正在用户界面(UI)线程上运行。  ;当你设置一个项目,然后使用Sleep停止UI线程,UI线程正在运行你的睡眠功能,因此没有绘制用户界面。

Your MainPage constructor is running on the User Interface (UI) thread.  When you set an item, then stall the UI thread with Sleep, The UI thread is running your sleep function, and therefore isn't drawing the user interface.

你需要什么do是将这样的工作传递给后台线程,或者使用一些异步函数来排队更改UI的工作

What you'll have to do is pass work like that to a background thread, or use some async functions to queue the work that changes the UI

以下是使用DispatcherTimer执行此操作的方法:

Here is the way you could do it with a DispatcherTimer:

        DispatcherTimer _timer;        
        public MainPage()
        {
            InitializeComponent();

            output.Text = "test";
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(5);
            _Timer.Tick += Tick;
            _Timer.Start();
                        
        }

        void Tick(object s, EventArgs args)
        {
            output.Text = "next";
            _timer.Stop();
        }


这篇关于为什么我看不到MainPage中TextBlock文本的每个更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆