How do I refresh visual control properties (TextBlock.text) set inside a loop?

前端 未结 5 943
醉梦人生
醉梦人生 2020-12-14 04:08

With each loop iteration, I want to visually update the text of a textblock. My problem is that the WPF window or control does not visually refresh until the loop is complet

5条回答
  •  一整个雨季
    2020-12-14 04:30

    This is how you would do it normally:

    ThreadPool.QueueUserWorkItem(ignored =>
        {
            for (int i = 0; i < 50; i++) {
                System.Threading.Thread.Sleep(100);
                myTextBlock.Dispatcher.BeginInvoke(
                    new Action(() => myTextBlock.Text = i.ToString()));
            }
        });
    

    This delegates the operation to a worker pool thread, which allows your UI thread to process messages (and keeps your UI from freezing). Because the worker thread cannot access myTextBlock directly, it needs to use BeginInvoke.

    Although this approach is not "the WPF way" to do things, there's nothing wrong with it (and indeed, I don't believe there's any alternative with this little code). But another way to do things would go like this:

    1. Bind the Text of the TextBlock to a property of some object that implements INotifyPropertyChanged
    2. From within the loop, set that property to the value you want; the changes will be propagated to the UI automatically
    3. No need for threads, BeginInvoke, or anything else

    If you already have an object and the UI has access to it, this is as simple as writing Text="{Binding MyObject.MyProperty}".

    Update: For example, let's assume you have this:

    class Foo : INotifyPropertyChanged // you need to implement the interface
    {
        private int number;
    
        public int Number {
            get { return this.number; }
            set {
                this.number = value;
                // Raise PropertyChanged here
            }
        }
    }
    
    class MyWindow : Window
    {
        public Foo PropertyName { get; set; }
    }
    

    The binding would be done like this in XAML:

    
    

提交回复
热议问题