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

发布于 2024-09-30 04:36:39 字数 776 浏览 1 评论 0原文

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

编辑1.

我的代码:

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

所以

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

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

编辑2。

如果有人需要 WPF 中的解决方案,那么应该尝试以下操作:

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

Hello
Why I haven't access to my private control on form (e.g. ListBox) from a static method?
How to update control in this case?

EDIT 1.

my code:

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

and

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

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

EDIT 2.

If someone need solution in WPF then should try this:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

蛮可爱 2024-10-07 04:36:39

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

将其写在表单类中:

static Form1 frm;

和表单构造函数中:

frm = this;

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

静态方法中的某处:

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

i found another answer on the web

write this in the form class:

static Form1 frm;

and in the form constructor:

frm = this;

now we can use the variable "frm" for accessing all of controls on the form.

somewhere in a static method:

frm.myListBox.Items.Add("something");
孤君无依 2024-10-07 04:36:39

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

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

...并像这样调用它:

SomeMethod(MyListBox);

Update
有多种方法可以在 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();
    }
}

...并调用它:

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

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

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

Static methods cannot access instance state (such as a non-static control). Either remove static from the method declaration, or pass a reference to the control as argument to the method:

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

...and call it like so:

SomeMethod(MyListBox);

Update
There are different ways to do asynchronous things in the UI (now assuming winforms). I would recommend you to look into using BackgroundWorker (search here on SO; plenty of examples). If you really want to do it by creating threads on your own, here is one way to do that:

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

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

...and to call it:

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

You can also use the thread pool (preferred over creating your own threads, given that you don't expect them to run for very long):

ThreadPool.QueueUserWorkItem(state => SomeMethod());
单身狗的梦 2024-10-07 04:36:39

我刚刚找到了一种新的、不同的方法来从静态方法更新控件。但我们必须为我们的控件选择唯一的名称

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

I just found a new and different way to update a control from a static method. but we have to choose unique names for our controls

foreach (Form tmp in Application.OpenForms)
    foreach (System.Windows.Forms.Control temp in tmp.Controls)
        if (temp.Name == "textBox1")
            temp.Text = "it works :)";
缱倦旧时光 2024-10-07 04:36:39

您需要将对控件的引用传递给静态方法或包含它们的东西。静态方法无法访问非静态字段/方法/等。不要将您的控件声明为静态,我什至不确定它是否可能,但如果是,它会导致您甚至不想知道的问题。

you need to pass a reference to the control to your static method, or something that contains them. static methods cant access non static fields/methods/etc. dont declare your control as static, i'm not even sure if its possible, but if it was, it would cause you problems you dont even want to know about.

相权↑美人 2024-10-07 04:36:39

从静态方法将项目添加到列表框的最简单解决方案:

  1. 在Form1 上添加 public static ListBox frm;
  2. 在 InitializeComponent() 之后添加 frm = this.listBox1;
  3. 从静态方法调用 Form1.frm.Items.Add(myitem)

easiest solution for adding an item to a listbox from a static method:

  1. Add on your Form1 public static ListBox frm;
  2. After InitializeComponent() add frm = this.listBox1;
  3. from your static method call Form1.frm.Items.Add(myitem)
[浮城] 2024-10-07 04:36:39

您无法从静态函数访问“this”、“ui”或 MainWindow 中的任何函数。

创建一个Mainwindow的公共指针

Mainwindow *THIS;

为了解决这个问题,在调用回调函数(静态函数)之前先

THIS=this;

,将this赋给指针THIS ,现在可以使用THIS来代替this。

例如:

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

You cannot access "this", "ui" or any function in MainWindow from a static function.

To solve this problem, make a public pointer of Mainwindow

Mainwindow *THIS;

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

THIS=this;

Now, you can use THIS instead of this.

for example:

THIS->listBox->Items->Add("Some element");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文