How to update controls from a static method?

Hi Why don't I have access to personal form controls (like ListBox) from a static method? How to update management in this case?

EDIT 1.

my code is:

ThreadStart thrSt = new ThreadStart(GetConnected);
        Thread thr = new Thread(thrSt);
        thr.Start();

and

static void GetConnected()
    {
        //update my ListBox
    }

So it must be invalid, without param and be static, right?

EDIT 2.

If someone needs a solution in WPF, try the following:

private void GetConnected()
    {
        myListBox.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(() =>
                    {
                        myListBox.Items.Add("something");
                    }
                               )
                 );
    }
+5
source share
5 answers

(, ). static , :

private static void SomeMethod(ListBox listBox)
{
    listBox.Items.Add("Some element");
}

... :

SomeMethod(MyListBox);


( winforms). BackgroundWorker ( SO; ). , , :

private void SomeMethod()
{
    string newElement = FetchNextElementToAdd():
    SafeUpdate(() => yourListBox.Items.Add(newElement));
}

private void SafeUpdate(Action action)
{
    if (this.InvokeRequired)
    {
        this.BeginInvoke(action);
    }
    else
    {
        action();
    }
}

... :

Thread thread = new Thread(SomeMethod);
thread.Start();

( , , , ):

ThreadPool.QueueUserWorkItem(state => SomeMethod());
+2

:

static Form1 frm;

:

frm = this;

"frm" .

- :

frm.myListBox.Items.Add("something");
+10

.

foreach (Form tmp in Application.OpenForms)
                foreach (System.Windows.Forms.Control temp in tmp.Controls)
                    if (temp.Name == "textBox1")
                        temp.Text = "it works :)";
+2

-, . // .. , , , , , .

+1

"this", "ui" MainWindow .

, Mainwindow

Mainwindow *THIS;

before calling the callback function (static function), assign this to the IT pointer

THIS=this;

Now you can use IT instead.

eg:

THIS->listBox->Items->Add("Some element");
0
source

All Articles