简体   繁体   English

更改另一个窗体上的控件的属性

[英]Changing the property of a control on another form

Basically, I have a settings window, and when you click "OK", it's suppose to apply settings to the main form (eg, set font of a control, etc), and then close. 基本上,我有一个设置窗口,当您单击“确定”时,应该将设置应用于主窗体(例如,设置控件的字体等),然后关闭。

frmmain frm = new frmmain();
frm.OLVAltBackColor = Color.Aquamarine ;

I tried that, but it only applies the settings to that instance, and you can see it if you do frm.Show(); 我尝试过,但是它仅将设置应用于该实例,如果您执行frm.Show(),则可以看到它。

I'm trying to make it so the already opened form has it's control's properties changed. 我正在尝试使它已经打开的窗体具有控件的属性已更改。

将属性更改应用于已存在且已显示的表单,而不是创建新表单并进行更改。

In this code you're creating a new instance of the frmmain. 在此代码中,您将创建frmmain的新实例。 Any changes you make to that new object will happen in the new object, not the one you actually want to change.: 您对该新对象所做的任何更改都会在新对象中发生,而不是您实际要更改的对象。

frmmain frm = new frmmain(); //Creating a new object isn't the way.
frm.OLVAltBackColor = Color.Aquamarine ;

What you're looking for is a way to call on the already existant frmmain class and change the property of that. 您正在寻找的是一种调用已经存在的frmmain类并更改其属性的方法。

Edit, for example: 编辑,例如:

using System;
class Statmethod
{
  //A class method declared
  static void show()
  {
    int x = 100;
    int y = 200;
    Console.WriteLine(x);
    Console.WriteLine(y);
  }

  public static void Main()
  {
    // Class method called without creating an object of the class
    Statmethod.show();
  }
}

What you are trying to do is not working because you are creating a NEW instance of your main form and updating that rather than the first instance. 您尝试执行的操作不起作用,因为您正在创建主窗体的实例并更新该实例而不是第一个实例。 It is possible to update the main form by keeping a reference to it in your settings form... but ... 可以通过在设置表单中保留对主表单的引用来更新主表单... 但是 ...

...it sounds like you are approaching this from the wrong direction. ...听起来好像您是从错误的方向走过来。

Don't make the settings form dependent on the main form. 不要使设置表单依赖于主表单。 Instead create the settings form from the main dialog. 而是从主对话框创建设置表单。

class SettingsForm : Form
{
   // You need to ensure that this color is updated before the form exits
   // either make it return the value straight from a control or set it 
   // as the control is updated
   public Color OLVAltBackColor
   {
       get;
       private set;
   }
}

In your main form (I'm assuming some kind of button or menu click) 在您的主要表单中(我假设某种按钮或菜单单击)

private void ShowSettingsClicked(object sender, EventArgs args)
{
   using (SettingsForm settings = new SettingsForm())
   {
       // Using 'this' in the ShowDialog parents the settings dialog to the main form
       if (settings.ShowDialog(this) == DialogResult.OK)
       {
           // update settings in the main form
           this.OLVAltBackColor = settings.OLVAltBackColor;
       }
   }

}

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

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