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

前端 未结 5 931
醉梦人生
醉梦人生 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:11

    If you really want the quick and dirty implementation and don't care about maintaining the product in the future or about the user experience, you can just add a reference to System.Windows.Forms and call System.Windows.Forms.Application.DoEvents():

    for (int i = 0; i < 50; i++)
    {
        System.Threading.Thread.Sleep(100);
        MyTextBlock.Text = i.ToString();
        System.Windows.Forms.Application.DoEvents();
    }
    

    The downside is that it's really really bad. You're going to lock up the UI during the Thread.Sleep(), which annoys the user, and you could end up with unpredictable results depending on the complexity of the program (I have seen one application where two methods were running on the UI thread, each one calling DoEvents() repeatedly...).

    This is how it should be done:

    1. Any time your application has to wait for something to happen (ie a disk read, a web service call, or a Sleep()), it should be on a separate thread.
    2. You should not set TextBlock.Text manually - bind it to a property and implement INotifyPropertyChanged.

    Here is an example showing the functionality you've asked for. It only takes a few seconds longer to write and it's so much easier to work with - and it doesn't lock up the UI.

    Xaml:

    <StackPanel>
        <TextBlock Name="MyTextBlock" Text="{Binding Path=MyValue}"></TextBlock>
        <Button Click="Button_Click">OK</Button>
    </StackPanel>
    

    CodeBehind:

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }
    
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 50; i++)
                {
                    System.Threading.Thread.Sleep(100);
                    MyValue = i.ToString();
                }
            });
        }
    
        private string myValue;
        public string MyValue
        {
            get { return myValue; }
            set
            {
                myValue = value;
                RaisePropertyChanged("MyValue");
            }
        }
    
        private void RaisePropertyChanged(string propName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
    

    The code might seem a bit complicated, but it's a cornerstone of WPF, and it comes together with a bit of practice - it's well worth learning.

    0 讨论(0)
  • 2020-12-14 04:13

    I tried the solution exposed here and it didn't work for me until I added the following:

    Create an extension method and make sure you reference its containing assembly from your project.

    public static void Refresh(this UIElement uiElement){
        uiElement.Dispatcher.Invoke(DispatcherPriority.Background, new Action( () => { }));
    }
    

    Then call it right after RaisePropertyChanged:

    RaisePropertyChanged("MyValue");
    myTextBlock.Refresh();
    

    That will force the UI thread to take control for a small while and dispatch any pending changes on the UI element.

    0 讨论(0)
  • 2020-12-14 04:28
    for (int i = 0; i < 50; i++)
    {
        System.Threading.Thread.Sleep(100);
        myTextBlock.Text = i.ToString();                
    }
    

    Running the above code inside a background worker component and using a binding updatesourcetrigeer as propertychanged will reflect the changes immediately in the UI control.

    0 讨论(0)
  • 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:

    <TextBlock Text="{Binding PropertyName.Number}" />
    
    0 讨论(0)
  • 2020-12-14 04:30

    You can do Dispatcher.BeginInvoke in order to do a thread context-switch so that the rendering thread could do its job. However, this is not the right way for such things. You should use Animation + Binding for things like that, as this is the hack-free way of doing things like that in WPF.

    0 讨论(0)
提交回复
热议问题