c# - 从另一个类访问表单控件

标签 c#

我有一个 Windows 窗体应用程序,其中一些控件已添加到设计器中。当我想更改某些内容(例如)启用 Form1.cs 中的文本框时,我只需使用:

textBox1.Enabled = true;

但现在我有一个名为 class1.cs 的独立类。

如何从静态函数 class1.cs 启用 textBox1?

注意:我没有尝试任何代码,因为我对此一无所知。

最佳答案

编辑:大量编辑。

public partial class Form1 : Form
{
    // Static form. Null if no form created yet.
    private static Form1 form = null;

    private delegate void EnableDelegate(bool enable);

    public Form1()
    {
        InitializeComponent();
        form = this;
    }

    // Static method, call the non-static version if the form exist.
    public static void EnableStaticTextBox(bool enable)
    {
        if (form != null)
            form.EnableTextBox(enable);
    }

    private void EnableTextBox(bool enable)
    {
        // If this returns true, it means it was called from an external thread.
        if (InvokeRequired)
        {
            // Create a delegate of this method and let the form run it.
            this.Invoke(new EnableDelegate(EnableTextBox), new object[] { enable });
            return; // Important
        }

        // Set textBox
        textBox1.Enabled = enable;
    }
}

关于c# - 从另一个类访问表单控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12983427/

相关文章:

c# - Entity Framework 无法在 Web.config 中找到连接字符串

c# - 合并两个有序的 IObservables

c# - C# 返回问题

c# - 使用 Visual Studio 2010 (VSTO) 进行 Office 开发,需要考虑的事项

c# - ASP.NET core 中第三方数据上下文的依赖注入(inject)

c# - 如何使用 C++ 非托管库在 Visual Studio 2017 中为 Xamarin.Forms 设置项目?

c# - 寻找一种有效的方法来使用 Entity Framework Core 为每一行检索一组多对多子项

c# - 使用 Serilog 时如何覆盖 appsettings.json 中指定的应用程序名称?

C#/WPF - 获取 ScrollViewer 滚动位置?

c# - protobuf-net:序列化一个空列表