winforms C#通过按钮刷新窗体(在同一窗体上)以显示初始控件值

bihw5rsg  于 2023-06-24  发布在  C#
关注(0)|答案(2)|浏览(158)

编辑:版本:4.0.30319.42000
我在想最简单的办法。
我有一个表单与多种控件类型。在窗体加载之前,我有一个例程从设置文件加载窗体控件的值。然后我使用Application调用窗体打开。
我有一个on_change例程,它知道任何表单控件的值何时更改,并显示一个CANCEL按钮。
我希望能够让用户按下这个取消按钮,并恢复到每个控件的原始值(在下面的代码示例中,我的盒子)。而不关闭表单(并失去其可见性)。
我不想再重新加载表格。我希望我能用FormState做些什么,但我不确定这将如何工作。
下面是一些示例代码:

public class Settings
{
     public static string MYPathFile_M = "";
}

public class MYClass
{
     [STAThread]
     public void main()
     {
          if(!fileExists())  //  Verifies setting file exists and reads in to variables
          {
               Application.EnableVisualStyles();
               Application.Run(new MYFORM_FORM());
          }
     }

     public bool fileExists()  // SIMPLIFIED FOR SPACE...
     {
          // if(!File.Exists ....
          // Open and read settings file
          // Load settings from file into public class Settings variables
          return true;
     }
}

public class MYFORM_FORM : Form
{
     public string result = null;

     public MYFORM_FORM()
     {
          // MY FORM SETTINGS
          this.ClientSize = new Size(1452, 577);
          this.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
          this.Margin = new Padding(2, 4, 2, 4);
          this.FormBorderStyle = FormBorderStyle.FixedDialog;
          this.MaximizeBox = false;
          this.MinimizeBox = false;
          this.ControlBox = false;
          this.StartPosition = FormStartPosition.CenterScreen;
          this.MinimumSize = new Size(this.Width, this.Height);
          this.MaximumSize = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
          int FontSize = 12;
          int ControlSpacing = 15;
          this.FormClosing += new FormClosingEventHandler((sender, e) => MYFORM_FORM_FormClosing(sender, e));
          this.Load += new System.EventHandler((sender, e) => MYFORM_FORM_Load(sender, e));
          this.Name = "MYFORM_FORM";
          this.Text = "My Form Settings"; 

          // MY BOX SETTINGS
          RichTextBox MYBox = new RichTextBox();
          MYBox.Location = new Point(12, 313);
          MYBox.Name = "MYBox";
          MYBox.ReadOnly = false;
          MYBox.ScrollBars = RichTextBoxScrollBars.Vertical;
          MYBox.ShortcutsEnabled = false;
          MYBox.Size = new System.Drawing.Size(938, 56);
          MYBox.TabIndex = 10;
          MYBox.Text = Settings.MYPathFile_M;  // Is a file path variable from public class Settings
          this.Controls.Add(MYBox);
          MYBox.BringToFront();

          // MY CANCEL BUTTON SETTINGS
          Button Cancel_Button = new Button();
          Cancel_Button.AutoEllipsis = true;
          Cancel_Button.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
          Cancel_Button.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Gray;
          Cancel_Button.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
          Cancel_Button.Location = new Point(1035, 517);
          Cancel_Button.Name = "Cancel_Button";
          Cancel_Button.Text = "CANCEL";
          Cancel_Button.Size = new Size(200, 48);
          Cancel_Button.Visible = false;  // Will be made true when there's a change on the form
          Cancel_Button.TabIndex = 20;
          Cancel_Button.UseVisualStyleBackColor = true;
          Cancel_Button.Click += new EventHandler((sender, e) => Cancel_Button_Clicked(sender, e));
          this.Controls.Add(Cancel_Button);

          Functions.ShowForm(this);
     }
     
     private void Cancel_Button_Clicked(object sender, EventArgs e)
     {
          if(Global.SaveChanges)  // Returns TRUE if there were changes on the form
          {
               DialogResult dr = MessageBox.Show("Are you sure you wish to cancel changes?","", MessageBoxButtons.YesNo);
               switch(dr)
               {
                    case DialogResult.Yes:
                    this.Controls["Cancel_Button"].Visible = false;
                    //  WHAT CODE COULD BE PLACED HERE TO ACCOMPLISH WHAT I'M TRYING TO DO??  //
                    //  FORM ORIGINAL VALUES SHOULD BE REINSTATED AND CANCEL BUTTON DISAPPEARS //
                    break;
                    case DialogResult.No:
                    break;
               }
     }
     else { this.Close(); }
     }
}

public class Functions
{
     public static void ShowForm(Form f)
     {
          IntPtr myHandle = f.Handle;
          SetForegroundWindow(myHandle.ToInt32());
     }

     [DllImport("User32.dll")]
     public static extern Int32 SetForegroundWindow(int hWnd);
}

希望可以在Cancel Button例程中放置一些相对简单的东西,以便能够将窗体的控件恢复为开始时加载的初始值。
我不确定最好的方法。

soat7uwm

soat7uwm1#

@吉米
是的,它是Net框架4.8,不支持空值。有点卡住了,因为在下面的第一行中得到“Invalid token '=' in class,struct,or interface member declaration”。
我也不知道MySettings()是如何使用的。
不可否认,你使用的一些概念仍然超出了我的经验。

public class Settings
{
    public string MYPathFile_M { get; set; } = ""; // File Path/Executable
    //public bool MYTrack { get; set; } = false; // User Track Boolean
    //public int MYNUM { get; set; } = 0; // Display Info Number
    
    public Settings Clone()   // Generates a new Settings object with stored values
    { return new MySettings() { MYPathFile_M = this.MYPathFile_M };
}
7d7tgy0s

7d7tgy0s2#

注意:我在这里使用空值,如:

public static Settings? defaultSettings = null;

如果您的.NET版本不支持此功能,请从声明中删除?
不是空条件运算符(它从C# 6开始就存在),如:

settings = MYClass.defaultSettings?.Clone();

更改Settings类,使其使用属性而不是Fields。
添加一个方法(此处命名为Clone()),该方法使用存储的值生成一个新对象:

public class Settings
{
    public string MYPathFile_M { get; set; } = "";
    // Other Properties

    public Settings Clone() {
        // Generates a new Settings object with stored values
        return new Settings() {
            MYPathFile_M = this.MYPathFile_M
        };
    }
}

在主类中,分配从文件中获得的值。
请注意,在代码中有if(!fileExists()) { },这没有多大意义

public class MYClass
{
    public static Settings? defaultSettings = null; 

    [STAThread]
    static void Main()
    {
      if(fileExists()) {
           Application.EnableVisualStyles();
           Application.Run(new MYFORM_FORM(defaultSettings.Clone()));
      }
        public bool fileExists()
        {
            // [...]
            defaultSettings = new Settings {
                MYPathFile_M = "Some value from file",
                // Other Properties
            };
            return true;
        }
    }
}

在窗体中,添加一个接受Settings对象的构造函数。该构造函数调用默认构造函数,该构造函数负责接口的初始化。
然后,InitializeSettingsBindings()方法将Controls的属性绑定到Settings类对象的Properties。在UI中更改绑定属性的值时,Settings对象的相应属性的值也会相应更新:

public class MYFORM_FORM : Form {

    private Settings? settings = null;
    private BindingSource? settingsSource = null;

    public MYFORM_FORM() {
        // [Your current initialization];
        // Remove MYBox.Text = Settings.MYPathFile_M;, not used here
    }

    internal MYFORM_FORM(Settings initialSettings) : this() {
        settings = initialSettings;
        if (settings != null) {
            settingsSource = new BindingSource(settings, null);
            InitializeSettingsBindings();
        }
    }

    // Initialize the Controls' bindings
    private void InitializeSettingsBindings() {
        MYBox.DataBindings.Add("Text", settingsSource, nameof(settings.MYPathFile_M), false, DataSourceUpdateMode.OnValidation);

        // You could also use InitializeSettingsBindings() to just set    
        // Properties of Controls directly. Then call this method again when needed
        // MYBox.Text = settings.MYPathFile_M;
    }
}

取消按钮只是将绑定重置为您存储在MYClass中的原始值的副本。
请注意,在Form初始化中设置的事件处理程序与Cancel_Button_Clicked()方法的签名不匹配。在这里使用匹配的。

private void Cancel_Button_Clicked(object sender, EventArgs e)
 {
      if(Global.SaveChanges) {
           if (MessageBox.Show("Cancel changes?","", MessageBoxButtons.YesNo) == DialogResult.Yes) {
               settings = MYClass.defaultSettings?.Clone();
               if (settingsSource != null) settingsSource.DataSource = settings;
           }
      }
      else { Close(); }
 }

相关问题