如何从静态方法更新控件?

Sai*_*int 6 .net c# controls static wpf-controls

您好我为什么无法从静态方法访问表单上的私有控件(例如ListBox)?在这种情况下如何更新控件?

编辑1.

我的代码:

ThreadStart thrSt = new ThreadStart(GetConnected);
        Thread thr = new Thread(thrSt);
        thr.Start();
Run Code Online (Sandbox Code Playgroud)

static void GetConnected()
    {
        //update my ListBox
    }
Run Code Online (Sandbox Code Playgroud)

所以它必须是无效的,没有参数并且是静态的,对吧?

编辑2.

如果有人需要WPF中的解决方案,那么应该尝试这样:

private void GetConnected()
    {
        myListBox.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(() =>
                    {
                        myListBox.Items.Add("something");
                    }
                               )
                 );
    }
Run Code Online (Sandbox Code Playgroud)

Moh*_*n R 12

我在网上找到了另一个答案

在表单类中写这个:

static Form1 frm;
Run Code Online (Sandbox Code Playgroud)

并在表单构造函数中:

frm = this;
Run Code Online (Sandbox Code Playgroud)

现在我们可以使用变量"frm"来访问表单上的所有控件.

静态方法中的某个地方:

frm.myListBox.Items.Add("something");
Run Code Online (Sandbox Code Playgroud)

  • 哇!你刚刚结束了我的一天 非常感谢! (2认同)

Fre*_*örk 4

静态方法无法访问实例状态(例如非静态控件)。从方法声明中删除static,或者将对控件的引用作为参数传递给方法:

private static void SomeMethod(ListBox listBox)
{
    listBox.Items.Add("Some element");
}
Run Code Online (Sandbox Code Playgroud)

...并这样称呼它:

SomeMethod(MyListBox);
Run Code Online (Sandbox Code Playgroud)

更新
有不同的方法可以在 UI 中执行异步操作(现在假设为 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

...并称其为:

Thread thread = new Thread(SomeMethod);
thread.Start();
Run Code Online (Sandbox Code Playgroud)

您还可以使用线程池(优于创建自己的线程,因为您不希望它们运行很长时间):

ThreadPool.QueueUserWorkItem(state => SomeMethod());
Run Code Online (Sandbox Code Playgroud)