Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

c# - Wpf Label not being updated when using Thread.Sleep()

I have a Label the Content of which I would like to update after each second,after 3 seconds I only see the last string "Step 3..." What am I doing wrong and is there another way to achieve this if for some reason I cannot use Thread.Sleep():

View:

<Window x:Class="WpfApplication1.ScrollerView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Scroller" DataContext="{StaticResource scrollerVM}" Height="150" Width="300">
    <Grid>
        <ListBox ItemsSource="{Binding Messages}" Width="200" Height="50" BorderThickness="0" VerticalAlignment="Top" HorizontalAlignment="Left">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Label Content="{Binding Text}"  />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ListBox>
        <Button Width="70" Height="24" Content="Add new" Command="{Binding AddNew}" HorizontalAlignment="Left" Margin="0,56,0,30" />
    </Grid>
</Window>

View model:

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading;

namespace WpfApplication1.Scroller
{
    public class Message
    {
        public Message(string _text)
        {
            text = _text;
        }

        private string text;
        public string Text
        {
            get { return text; }
            set {text = value;}
        }
    }

    public class ScrollerViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public DelegateCommand AddNew { get; protected set; }

        ObservableCollection<Message> _messages = new ObservableCollection<Message>();
        public ObservableCollection<Message> Messages
        {
            get { return _messages; }
            set
            {
                _messages = value;
                OnPropertyChanged("Messages");
            }
        }

        public ScrollerViewModel()
        {
            AddNew = new DelegateCommand(Add);
        }

        private void Add(object parameter)
        {
            UpdateProgress("Step 1...");
            UpdateProgress("Step 2...");
            UpdateProgress("Step 3...");
        }

        private void UpdateProgress(string step)
        {
            Messages.Clear();
            Messages.Add(new Message(step));
            Thread.Sleep(1000);
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is because you are sleeping in the UI thread. The UI won't have a chance to update until Add is finished. You can use a BackgroundWorker with ReportProgress to achieve what you want. Something like this:

BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
    worker.ReportProgress(1, "Step1");
    Thread.Sleep(1000);
    worker.ReportProgress(2, "Step2");
    Thread.Sleep(1000);
    worker.ReportProgress(3, "Step3");
};
worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args)
{
    string step = (string)args.UserState;
    Messages.Clear();
    Messages.Add(new Message(step));
};
worker.RunWorkerAsync();

The UI thread won't be occupied while DoWork is executed, but the code in ProgressChanged will be performed on the UI thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...