Updating WPF Controls at Run Time

I am trying to write a WPF application that will update a set of text fields and labels at runtime using threads, but the problem is that when a thread tries to update text fields and labels, I get the following error: "The calling thread cannot access this object because it owns another thread. " Is it possible to update the control at runtime?

+3
source share
3 answers

Yes, but you must update the user interface elements in the user interface stream using Dispatcher.Invoke .

Example in C #: instead

myTextBox.Text = myText;

using

Dispatcher.Invoke(new Action(() => myTextBox.Text = myText));

VB.NET (before version 4) does not support anonymous methods, so you have to deal with an anonymous function:

Dispatcher.Invoke(Function() UpdateMyTextBox(myText))

...

Function UpdateMyTextBox(ByVal text As String) As Object
    myTextBox.Text = text
    Return Nothing
End Function

Alternatively, you can start your background threads using the BackgroundWorker class , which supports updates in the user interface through ProgressChangedand RunWorkerCompletedevents: both events automatically occur in the user interface stream. An example of using BackgroundWorker can be found here: SO question 1754827 .

+4
source

WPF Dispatcher, Invoke, , GUI.

myCheckBox.Dispatcher.Invoke(DispatcherPriority.Normal,
                             () => myCheckBox.IsChecked = true);
+2

For a detailed explanation of the streaming WPF model, including how the dispatcher works, skip to minute 17 in this video from the Hiking Mount Avalon Workshop in Mix09.

+1
source

Source: https://habr.com/ru/post/1732320/


All Articles