【问题标题】:Changing properties of a button via method from another class通过另一个类的方法更改按钮的属性
【发布时间】:2022-10-20 17:38:39
【问题描述】:

也许你可以帮我解决我的问题。

我的类“Form1”调用方法 setButtons();

但 setButtons() 不在“Form1”类中,它在“Class1”类中。

在“Class 1”中设置 Buttons() 无法识别 Form1 中的 Button1。

我如何让它知道 Button1 存在于 Form1 中,并且我希望该方法在“Form1”中的 Button1 上工作? Class1 已经有一个指向 Form1 的使用目录,而 Form1 有一个指向 Class1 的目录。

//this does not work
public static void setbuttons()
{
    Form1.Button1.Location = new Point(40, 40);
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    我发现如果你像这样在设计器文件中声明一个公共控件

    public Button button1;
    

    然后,您可以在获得表单对象的条件下从另一个类访问它,例如作为扩展

    static class AnotherClass
    {
        public static void setButtons(this Form1 form)
        {
            form.button1.Text = "Hello";
        }
    }
    

    就设计和代码管理而言,更改按钮属性的更好方法是在您的表单中创建一个方法来执行此操作。

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            ...
        }
    
        public void ChangeButtonTextMethod(string text)
        {
            button1.Text = text;
        }
    }
    

    【讨论】:

    • 你可以这样做,但这不是很好的设计。通常,允许其他类、控件、表单等操作此类中的 UI 会导致非常紧密耦合的代码很脆弱。我不会这样做,而是在表单上公开一个带有按钮的方法,该按钮只接受按钮文本的string 参数。
    • @AvrohomYisroel 是的,我也会这样做。我提出了这种方法,因为该问题专门要求一种从外部类操作控件的方法。以防万一,我会将其添加到答案中。
    • 明白了,但是当这不是一个好方法时,我会谨慎回答 OP 的要求。总是更好地提出更优化的方法。
    • 好多了!赞成
    【解决方案2】:

    考虑使用一个事件,其中 Class1 中的方法将一个 Point 传递给侦听该事件的调用表单,在本例中为 SetButtons。

    public class Class1
    {
        public delegate void OnSetLocation(Point point);
        public static event OnSetLocation SetButtonLocation;
    
        public static void SetButtons()
        {
            SetButtonLocation!(new Point(40, 40));
        }
    }
    

    在订阅 SetButtonLocation 的表单中,调用 SetButtons 方法,该方法将 Point 传递给 Form1 中的调用者,然后设置按钮位置。

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            Class1.SetButtonLocation += OnSetButtonLocation;
            Class1.SetButtons();
            Class1.SetButtonLocation -= OnSetButtonLocation;
        }
    
        private void OnSetButtonLocation(Point point)
        {
            button1.Location = point;
        }
    }
    

    使用这种方法比如前所述将 form 的修饰符更改为 public 更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      相关资源
      最近更新 更多