简体   繁体   中英

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();

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. 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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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