簡體   English   中英

更改另一個窗體上的控件的屬性

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

基本上,我有一個設置窗口,當您單擊“確定”時,應該將設置應用於主窗體(例如,設置控件的字體等),然后關閉。

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

我嘗試過,但是它僅將設置應用於該實例,如果您執行frm.Show(),則可以看到它。

我正在嘗試使它已經打開的窗體具有控件的屬性已更改。

將屬性更改應用於已存在且已顯示的表單,而不是創建新表單並進行更改。

在此代碼中,您將創建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();
  }
}

您嘗試執行的操作不起作用,因為您正在創建主窗體的實例並更新該實例而不是第一個實例。 可以通過在設置表單中保留對主表單的引用來更新主表單... 但是 ...

...聽起來好像您是從錯誤的方向走過來。

不要使設置表單依賴於主表單。 而是從主對話框創建設置表單。

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM