C# 从另一个类访问表单的控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12983427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:12:59  来源:igfitidea点击:

Accessing Form's Controls from another class

c#

提问by Roman Ratskey

I have a windows forms application with some controls added to the designer. When i want to change something (LIKE) Enable a text box from inside the Form1.cs

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

i simply use

我只是使用

textBox1.Enabled = true;

but now i have a separated class called class1.cs

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

How could i enable textBox1 from a static function class1.cs ?

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

{NOTE} I did not tried any code because i am totally clueless about doing this.

{注意}我没有尝试任何代码,因为我对这样做完全一无所知。

采纳答案by LightStriker

EDIT: Lot of edit.

编辑:大量编辑。

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;
    }
}

回答by Lews Therin

You could let your class1 have an event to enable the Textbox.

你可以让你的 class1 有一个事件来启用文本框。

public class Class1
{
  public event Action<object, EventArgs> subscribe ;
  private void raiseEvent()
  {
     var handler = subscribe ;
     if(handler!=null)
     {
        handler(this,EventArgs.Empty);//Raise the enable event.
     }
  }
}

Let the class containing the TextBox subscribe to it somehow. In TextBox wrapper class

让包含 TextBox 的类以某种方式订阅它。在 TextBox 包装类中

 public class TextBoxWrapper
       public void EnablePropertyNotification(object sender, EventArgs args) 
       {
          TextBox1.Enabled = true ; //Enables textbox when event is raised.
       }
       public TextBoxWrapper()
       {
         class1Instance.subscribe+=EnablePropertyNotification ;
       }

回答by codingbiz

You can pass the instance of your Form to the class

您可以将 Form 的实例传递给类

 MyForm frm = new MyForm();

 MyClass c = new MyClass(frm);

Then your class can take that instance and access the textbox

然后您的班级可以采用该实例并访问文本框

 public class MyClass
 {

   public MyClass(MyForm f)
   {
      f.TextBox1.Enabled = false;
   }
 }

The design does not look OK

设计看起来不太好

It is better to call the class in your form and based on the value returned, manipulate the textbox

最好在您的表单中调用该类并根据返回的值,操作文本框

//MyForm Class

 MyClass c = new MyClass();
 c.DoSomethings();
 if(c.getResult() == requiredValue)
   textBox1.enabled = true;
 else
   textBox1.enabled = false;

//MyForm Class ends here

UPDATE

更新

public class Class1
{
   public static int SomeFunction()
   {
      int result = 1;
      return result;
   }

   public static void SomeFunction(out int result)
   {
      result = 1;
   }
}

Usage

用法

if(Class1.SomeFunction() == 1)
   textBox1.Enabled = true;
else
   textBox1.Enabled = false;

OR

或者

int result = 0;
Class1.SomeFunction(out result);

if(result == 1)
   textBox1.Enabled = true;
else
   textBox1.Enabled = false;

回答by Mario Sannum

You shouldn't really change UI controls in your Formfrom your class1, but instead create a method or a property in class1that would tell if the textbox should be enabled or not.

您不应该真正Formclass1更改 UI 控件,而是在class1中创建一个方法或属性来判断是否应该启用文本框。

Example:

例子:

// I changed the name class1 to MySettings
public class MySettings
{
    public bool ShouldTextBoxBeEnabled()
    {
        // Do some logic here.
        return true;
    }

    // More generic
    public static bool SetTextBoxState(TextBox textBox)
    {
        // Do some logic here.
        textBox.Enabled = true;
    }

    // Or static property (method if you like)
    public static StaticShouldTextBoxBeEnabled { get { return true; } }
}

Then in your form:

然后以您的形式:

MySettings settings = new MySettings();
textBox1.Enabled = settings.ShouldTextBoxBeEnabled();

// Or static way
textBox1.Enabled = MySettings.StaticShouldTextBoxBeEnabled;

// Or this way you can send in all textboxes you want to do the logic on.
MySettings.SetTextBoxState(textBox1);

回答by Hassan Eskandari

This is how you should do : I wrote the code below in my form class :

这是你应该怎么做:我在我的表单类中编写了下面的代码:

public static Form1 form = null;

    private delegate void SetImageDelegate(Image image);

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

    public static void SetStaticImage(Image image)
    {
        if (form != null)
            form.pic1.Image = image;
    }

    private void setImage(Image img)
    {
        // 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 SetImageDelegate(setImage), new object[] { img });
            return; // Important
        }

        // Set textBox
        pic1.Image = img;
    }

and the code below should be in anouther class :

并且下面的代码应该在另一个类中:

Form1 frm= Form1.form;
frm.pic1.Image = image;

Note that i changed private static Form1 form = null;to public static Form1 form = null;

请注意,我更改private static Form1 form = null;public static Form1 form = null;

Good Luck ... Written by Hassan Eskandari :)

祝你好运......由哈桑·埃斯坎达里 (Hassan Eskandari) 撰写 :)

回答by vr_driver

This is just another method:

这只是另一种方法:

TextBox t = Application.OpenForms["Form1"].Controls["textBox1"] as TextBox;

回答by noel

I had to do this at work and didn't find that any of these answers matched what I ended up doing, so I'm showing how I made it work.

我不得不在工作中这样做,但没有发现这些答案中的任何一个与我最终所做的相符,所以我展示了我是如何使它工作的。

First, initialize a copy of your class in your load event.

首先,在加载事件中初始化类的副本。

NameOfClass newNameofClass;

Then you want to bind to your class (in the load event):

然后你想绑定到你的类(在加载事件中):

textBox1.DataBindings.Add(new Binding("Enabled", newNameofClass, "textBox1Enabled"));

In your class, do the following:

在您的班级中,执行以下操作:

private bool textBox1Enabled = false;
public bool TextBox1Enabled
{
    get
        {
            return textBox1Enabled;
        }
        set
        {
            textBox1Enabled = value;
        }
}
  • The false setting will initialize your textbox to being disabled
  • Set textBox1Enabled to true if you want to enable by default.
  • If you have other logic to enable/disable the textbox, simply modify the value of textBox1Enabled accordingly.
  • false 设置会将您的文本框初始化为被禁用
  • 如果要默认启用,请将 textBox1Enabled 设置为 true。
  • 如果您有其他逻辑来启用/禁用文本框,只需相应地修改 textBox1Enabled 的值。

回答by Ali Sajjad

To access/modify a Form Element property, just write this in your outside Class.

要访问/修改表单元素属性,只需在您的外部类中写入即可。

Form1.ActiveForm.Controls["textBox1"].Enabled = true;

Where 'textBox1' is the variable name of TextBox.

其中 'textBox1' 是 TextBox 的变量名。

What this actually does: Gets the active Form object's control specified by the name in string.

这实际上是做什么的:获取由字符串中的名称指定的活动 Form 对象的控件。

WARNING: Active form means the form which is currently open and focused on. If you do something else on your computer, with your minimized WindowsForm application, the Form1.ActiveForm will not get the form, instead, it will give 'null', which can lead to errors later. Be careful!

警告:活动表单是指当前打开并关注的表单。如果您在计算机上使用最小化的 WindowsForm 应用程序执行其他操作,Form1.ActiveForm 将不会获取该表单,而是会给出“null”,这可能会导致稍后出现错误。当心!

Best regards!

此致!