在另一个表单上更改控件的属性

时间:2009-10-31 15:46:23

标签: c# controls

基本上,我有一个设置窗口,当你点击“确定”时,它假设将设置应用于主窗体(例如,设置控件的字体等),然后关闭。

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

我试过了,但它只将设置应用于该实例,如果你做了frm.Show();你可以看到它。

我正在努力使它已经打开的表格让它的控件的属性发生了变化。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

在此代码中,您将创建frmmain的新实例。您对该新对象所做的任何更改都将在新对象中进行,而不是您实际想要更改的对象。

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

你正在寻找的是一种调用已经存在的frmmain类并改变它的属性的方法。

编辑,例如:

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

答案 2 :(得分:0)

您尝试执行的操作无效,因为您正在创建主表单的 NEW 实例并更新该实例而不是第一个实例。可以通过在设置表单中保留对其的引用来更新主表单... ...

......听起来你是从错误的方向接近这个。

不要使设置表单依赖于主窗体。而是从主对话框中创建设置表单。

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

在您的主要表单中  (我假设某种按钮或菜单点击)

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

}
相关问题