【问题标题】:Unable to update main form control from subclass无法从子类更新主窗体控件
【发布时间】:2016-10-17 23:09:00
【问题描述】:

尝试 #2。

我正在尝试调用两个类中的函数。一个函数获取数据并调用B类中的函数B,通过Windows窗体应用程序显示数据。

    //Class B containing function B
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GUI_Server
{
    public partial class ChatServer : Form
    {

        private delegate void EnableDelegate(bool enable);
        private static ChatServer CHT = new ChatServer();

        public ChatServer()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ServerBackBone.test();
        }

        public static void TestConnectivity(string text)
        {
            CHT.TestLabel.Text = text;
        }
    }
} // Assume Class B

下面是A类和函数A

   using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;


namespace GUI_Server
{
    class ServerBackBone
    {


        private static ChatServer CHT = new ChatServer();
        public static void test()
        {
            ChatServer.TestConnectivity("test");


        }


    }
}

所以,这里发生的事情是正在加载表单,调用类 A 中的静态函数来联系类 B > 函数 B 更新主窗口上的标签...问题在于更新标签与新文本。

单步执行代码表明所有函数都已成功调用,并且预期的文本已传递给函数。

虽然,当按 F5 开始调试所述应用程序时,诊断工具显示以下消息:

诊断工具意外失败

诊断中心输出显示:

响应状态码不表示成功:401(未授权)。

一般输出显示:

线程 0x20c0 已退出,代码为 0 (0x0)。

线程 0x1624 已退出,代码为 0 (0x0)。

'GUI Server.vshost.exe'(CLR v4.0.30319:GUI Server.vshost.exe): 已加载 'c:\users\shaiya\documents\visual studio 2015\Projects\GUI 服务器\GUI 服务器\bin\Debug\GUI Server.exe'。已加载符号。

线程 0x20fc 已退出,代码为 0 (0x0)。

线程 0xae8 以代码 0 (0x0) 退出。

显示这些消息后,应用程序成功运行。单步执行现在显示错误,断点也不显示。主控件中的标签也没有更新

全新的项目。实际表单界面上唯一的元素是属性重命名为TestLabel的标签。

 this.TestLabel = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // TestLabel
            // 
            this.TestLabel.AutoSize = true;
            this.TestLabel.Location = new System.Drawing.Point(43, 70);
            this.TestLabel.Name = "TestLabel";
            this.TestLabel.Size = new System.Drawing.Size(35, 13);
            this.TestLabel.TabIndex = 0;
            this.TestLabel.Text = "label1";

【问题讨论】:

    标签: c#


    【解决方案1】:

    我不确定Form1_Load 中的thisTestConnectivity 中的CHT 是同一个对象。它们必须是,因为您尝试更新的是 this

    【讨论】:

    • 也许是这样。块并且必须使用此方法是,当它备份和运行时,我在主应用程序中使用静态类功能。变通保持静止?
    • 将您的public static void Test() 更改为public static string Test(),以返回您要在表单上使用的值。如果是异步的,可以await或者使用事件监听器
    • 毫无疑问,这将解决当前的问题,我想到的问题是我最终将使用套接字来发送/接收数据,包括整数和字符串。在 Sockets 中看到的示例中,它使用了一个不返回任何内容并且可以随时调用的回调函数,那么人们将如何去监听一个使用单独的函数作为在后台运行的回调的事件呢?当接收到数据时,哪个也会更新主窗体?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    相关资源
    最近更新 更多