从子窗体设置父窗体参数
本文关键字:窗体 参数 设置 | 更新日期: 2023-09-27 18:08:59
我有一个使用c#表单的问题。我的主表单名为Form1,从中我可以打开一个名为x的子表单作为对话框。
当我调用子窗体x中的函数时,我希望所有其他窗体和主窗体都受到它的影响。
public void Change_Layout_Red(System.Windows.Forms.Control Container)
{
if (rb_EmberRed.Checked == true)
{
try
{
foreach (Control ctrl in Container.Controls)
{
if (ctrl.GetType() == typeof(TextBox))
((TextBox)ctrl).BackColor = Color.Red;
if (ctrl.GetType() == typeof(ComboBox))
((ComboBox)ctrl).BackColor = Color.Red;
if (ctrl.GetType() == typeof(DataGridView))
((DataGridView)ctrl).BackColor = Color.Red;
if (ctrl.GetType() == typeof(Label))
((Label)ctrl).ForeColor = Color.White;
if (ctrl.GetType() == typeof(TabPage))
((TabPage)ctrl).BackColor = Color.Black;
if (ctrl.GetType() == typeof(Panel))
((Panel)ctrl).BackColor = Color.Red;
if (ctrl.GetType() == typeof(RadioButton))
((RadioButton)ctrl).ForeColor = Color.White;
if (ctrl.Controls.Count > 0)
Change_Layout_Red(ctrl);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
当我单击子窗体中的按钮时,我希望该函数运行并应用于所有可用的窗体,它将像默认值一样。
private void btn_ChangeLayout_Click(object sender, EventArgs e)
{
Change_Layout_Red(Form1.ActiveForm);
}
此代码仅更改活动子窗体中的颜色。
首先,是否有一种方法可以使这个函数改变所有新打开的子表单的默认值?其次,我如何访问主表单Form1中的控件?我试图在第一个函数中添加Form1.((TextBoX)ctrl).Backcolor = Color.Red
,但它不起作用。
谢谢
您可以创建一个基本表单,并在其中添加一个属性,如
public virtual Layout Layout { get; set; } //Se below
然后,在子窗体中,您可以访问它的父窗体:
(Form1.Parent as MyCustomForm).Layout = new Layout(Color.Red);
在父窗体中,您可以迭代子窗体并更改其布局:
public virtual Layout Layout {
get {return _layout; }
set {
if (IsMdiContainer) {
foreach (MyCustomForm item in MdiChildren.Cast<MyCustomForm>()) {
item.Layout = value;
}
}
foreach (Control ctrl in Container.Controls) {
//Apply layout settings to controls
}
}
布局类可以是这样的:
class Layout {
public Layout(Color color) {
//Initialize the properties values based on the selected color
}
public Color TextBoxForeColor {get; set;}
public Color TextBoxBackColor {get; set;}
public Color LabelForeColor {get; set;}
public Color LabelBackColor {get; set;}
}