从具有不同形式的表单调用方法作为参数? [英] Calling method from a form with a different form as the argument?
问题描述
我有一个颜色对话框,一个用于设置表单的BackColor,但是我设置它的全局方法不会接受MainForm - 我的其他形式而不是设置表单 - 作为Form的参数方法。
以下是我的按钮代码:
I have a color dialog, one which is used to set the BackColor of the forms, however the global method I made to set it will not accept MainForm -- my other form than the settings form -- as the Form argument for the method.
Below is my code for the button:
private void button1_Click(object sender, EventArgs e)
{
AppBackgroundColorDialog.ShowDialog();
globalvariables.DefaultBackgroundColor = AppBackgroundColorDialog.Color;
globalvariables.SetBackColor(this);
//Below is what's in question
globalvariables.SetBackColor(MainForm);
/*I also tried what is beneath this comment, which works and makes more
sense, but results in two MainForm(s). I must also note that it does not
appear as well as simply changing the color of the already open form
would.*/
Form newmainform = new MainForm();
globalvariables.SetBackColor(newmainform);
newmainform.Show();
}
下面是我的全局变量类的代码和设置表单背景颜色的方法(毫无疑问,你可以毫无疑问)推断):
Below is the code for my global variables class and the method for setting form background color (as you can undoubtedly infer):
public class globalvariables
{
public static Color DefaultBackgroundColor = Color.FromArgb(255, 255, 255);
public static void SetBackColor(Form form)
{
form.BackColor = globalvariables.DefaultBackgroundColor;
}
}
我意识到MainForm是一种类型,而不是变量,但我不确定如何处理或如何设置背景颜色而不使用关闭MainForm,然后使用新设置的背景颜色重新打开它。我是否必须在MainForm中调用该方法,或者有没有办法从SettingsForm中执行此操作?
提前谢谢!
I realize MainForm is a type, not a variable, but I'm not sure what to do about that or how to set the background color without using closing MainForm, then reopening it with the newly set background color. Do I have to call the method from within MainForm, or is there a way to do so from SettingsForm?
Thank you in advance!
推荐答案
如果您想影响表单的当前实例,只需传递当前实例:
If you want to affect the current instance of the form, you just pass the current instance:
private void button1_Click(object sender, EventArgs e)
{
AppBackgroundColorDialog.ShowDialog();
globalvariables.DefaultBackgroundColor = AppBackgroundColorDialog.Color;
globalvariables.SetBackColor(this);
}
如果您要做的是从设置表单中更改调用设置表单的表单,那么它会更复杂 - 您应该做的是设置表格提高主窗体处理的事件 - 并且改变它自己的颜色(或者将它自己的实例传递给你的SetBackColor方法)。
听起来很复杂,但实际上并非如此:在两种表格之间转移信息,第2部分:儿童到家长 [ ^ ]解释了如何。
If what you are trying to do is alter the form that called the settings form from within the settings form, then it's more complex - and what you should do is have the settings form raise an event which the main form handles - and that changes it's own colour (or passes it's own instance to your SetBackColor method).
That sounds complicated, but it really isn't: Transferring information between two forms, Part 2: Child to Parent[^] explains how.
这篇关于从具有不同形式的表单调用方法作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!