简体   繁体   English

有关更新Winforms标签文本的问题

[英]Issue on updating winforms label text

I have a windows forms application I have a public class inside my form code behind with the following structure : 我有一个Windows窗体应用程序,我的窗体代码后面有一个公共类,其结构如下:

 public partial class Home : Form
 {
     public class AsynchronousSocketListener
     {
         public void ReadCallback(IAsyncResult ar)
         {
           //Here I want to Update a labels text this waw :
           //label1.Text = currantRFID;
         }
     }
 }

I can not access lablel1 control inside the ReadCallback() function and update It's text . 我无法访问lablel1 ReadCallback()函数内部的lablel1控件并更新它的text。 when I try to do that I get the following error : 当我尝试这样做时,出现以下错误:

Error 3 Cannot access a non-static member of outer type 'SFTWindowApplications.Home' via nested type 'SFTWindowApplications.Home.AsynchronousSocketListener'

how can I access It and what is the best way to update It's text ? 我如何访问它以及更新它的文本的最佳方法是什么? I mean is It better to update It Asynchronously or not ? 我的意思是最好还是Asynchronously更新它?

thx in advance . 提前。

A nested class (ie AsynchronousSocketListener ) does not automagically have access to the non-static members of its outer type (ie Home ). 嵌套类(即AsynchronousSocketListener )无法自动访问其外部类型(即Home )的非静态成员。

Restarting your IDE will not change this. 重新启动IDE不会更改此设置。 IntelliSense is doing what it should - not listing a member of an outer type that is not in scope. IntelliSense在做应做的事情-不列出不在范围内的外部类型的成员。

If you wish for the async listener to affect the form's label, an instance of AsynchronousSocketListener will need a reference to label1 ... 如果希望异步侦听器影响表单的标签,则AsynchronousSocketListener的实例将需要对label1的引用。

// Really this is just an example of how it could avoid the error you encountered -
// reality checked only by my cerebral compiler. :)
public partial class Home : Form
{
    // instance of the async socket listener to use
    private AsynchronousSocketListener asyncSocketListener; 

    public Home()
    {
        // Initialize the async socket listener, and provide to it a reference to
        // the label it should update.
        asyncSocketListener = new AsynchronousSocketListener(label1);
    }

    public class AsynchronousSocketListener
    {
        private Label targetLabel;

        public AsynchronousSocketListener(Label targetLabel)
        {
            this.targetLabel = targetLabel;
        }

        public void ReadCallback(IAsyncResult ar)
        {
            // // assuming currantRFID is part of the async result ar
            this.targetLabel.Text = ar.currantRFID;
        }
    }
}

..., or you need to take an event-driven approach. ...,或者您需要采用事件驱动的方法。

Ideally the relationship between the classes and what happens following a response would be less concrete & rigid (eg not specific to just a label, not requiring the classes to know so much about each other). 理想情况下,类与响应后发生的事情之间的关系应该不太具体和僵化(例如,不仅仅针对标签,不要求类之间彼此了解太多)。 An event-driven approach (ie the async listener raises an event to which this particular form subscribes and handles by updating its label) would achieve these goals. 一种事件驱动的方法(即,异步侦听器引发一个事件,该特定表单通过更新其标签来订阅和处理该事件)将实现这些目标。 But I am admittedly just trying to give you a sense how it could work with respect to the non-static member access that is at the center of the question you asked. 但是,我公认的是,我只是想让您了解如何解决非静态成员访问问题,后者是您提出问题的核心。

It's a different class, so you need to pass the label instance or pass the Home class instance to the method and make the label public (imo it's protected by default). 这是一个不同的类,因此您需要传递标签实例或将Home类实例传递给该方法并使标签公开(默认情况下,它是受保护的)。

UPDATE : New code with BackGroundWorker Note: I didn't test this code, but it should give you an idea. 更新 :使用BackGroundWorker的新代码注意:我没有测试此代码,但是它应该可以给您一个思路。

public partial class Home : Form
{
 public class AsynchronousSocketListener : IDisposable
 {
   private BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

   private Label myLabel;
   public AsynchronousSocketListener(Label lbl)
   {
       myLabel = lbl;
       worker.RunWorkerCompleted += WorkerCompleted;
       worker.DoWork += DoWork;
       worker.RunWorkerAsync();
   }
   public void Dispose()
    {
        worker.RunWorkerCompleted -= WorkerCompleted;
        worker.CancelAsync();
        worker.Dispose();
    }

   private void DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
   {
     // Perform your work on the other Thread
     e.Result = currantRFID;
   }

   public void WorkerCompleted(object sender, RunWorkerCompletedEventArgs args)
   {
      //Here I want to Update a labels text this waw :
      myLabel.Text = args.Result;
   }
         }
}




/*

    public partial class Home : Form
     {
         public class AsynchronousSocketListener
         {
             private Label myLabel;
             public AsynchronousSocketListener(Label lbl)
             {
                myLabel = lbl;
             }
             public void ReadCallback(IAsyncResult ar)
             {
               //Here I want to Update a labels text this waw :
               myLabel.Text = currantRFID;
             }
         }
     }

*/

尝试重新启动IDE,如果无济于事,请显示设计者代码。

You can't access member of one class inside other class without having any reference to parent class. 如果没有对父类的任何引用,则不能访问其他类中一个类的成员。 You need to access label1 inside ReadCallback through your Home class. 您需要通过Home类访问ReadCallback内部的label1

See this example 这个例子

You need to provide your Home-Class to the classes where you want to use the controls, eg 您需要向要使用控件的类提供“家庭班级”,例如

[...] new AsynchronousSocketListener(this) [...]新的AsynchronousSocketListener(this)

and pass it until you are in the depth where you need it. 并将其传递到需要的深处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM