我有这个项目,其中包含我的主要表单中的所有面板实例。
config.vm.network "private_network", ip: "192.168.33.12"
config.vm.network "public_network", ip: "192.168.33.13"
config.vm.network :public_network
这是program.cs启动时加载的形式。 因为我希望每个小组都有一个集中的地方,在其中调用另一个方法,因此我在main中声明它们。在main中,我还在一些方法中使用某些方法来执行某些功能,因为它们是在main中声明的。
PanelA aPanelA = new PanelA;
PanelB aPanelB = new PanelB;
问题是PanelA中的小部件如何通过main调用方法setPanelB()?
void setPanelA (int iNumber){...}
void setPanelB (string strString){...}
我知道我可以将PanelA和PanelB声明为静态。但这是唯一的方法吗?因为如果我向两个Panel声明静态,我将需要在Panel中将一些实例声明为静态..
我也不希望在PanelB中声明PanelA或反之亦然,因为我可能有很多类型的面板,这会使我的代码非常不整洁。
*已编辑我已在此处添加示例代码
Main.setPanelB("Hello World);
}
答案 0 :(得分:0)
以下代码演示了如何向Panel
类型和Form1
添加事件。通过这样做,您可以在Panel中引发Form1将注册处理的事件。
public partial class Form1 : Form
{
protected EventHandler<PanelEventArg> OnSetPanelA = new EventHandler<PanelEventArg>((sender, e) => { }); //stub
protected EventHandler<PanelEventArg> OnSetPanelB = new EventHandler<PanelEventArg>((sender, e) => { }); //stub
protected List<PanelBase> panels;
public Form1() : base()
{
panels = new List<PanelBase>
{
new PanelA(),
new PanelB()
};
foreach (var panel in panels)
{
OnSetPanelA += panel.OnSetPanel;
OnSetPanelB += panel.OnSetPanel;
panel.OnSomeEvent += Form1_OnSomeEvent;
}
foreach (var panel in panels.OfType<PanelB>())
{
panel.OnChangePanelA += Form1_OnChangePanelA;
}
InitializeComponent();
}
protected void SetPanelA(int iNew)
{
foreach (var panel in panels.OfType<PanelA>())
{
panel.SetPanelA(iNew);
OnSetPanelA(this, new PanelEventArg
{
Panel = panel
});
}
}
protected void SetPanelB(string strNew)
{
foreach (var panel in panels.OfType<PanelB>())
{
panel.SetPanelB(strNew);
OnSetPanelA(this, new PanelEventArg
{
Panel = panel
});
}
}
protected void Form1_OnSomeEvent(object sender, EventArgs e)
{
// handles events raised by the panel.
}
protected void Form1_OnChangePanelA(object sender, int iNew)
{
SetPanelA(iNew);
}
}
PanelEventArg
,PanelBase
public class PanelEventArg : EventArgs
{
public PanelBase Panel { get; set; }
}
public class PanelBase //: Panel
{
public EventHandler OnSomeEvent = new EventHandler((sender, e) => { }); //stub;
public void OnSetPanel(object sender, PanelEventArg e)
{
if (!Equals(e.Panel, this))
{
//the panel being set is not this panel instance
}
}
}
PanelA
和PanelB
,继承和PanelB
public class PanelA : PanelBase
{
int i = 0;
public void SetPanelA(int iNew)
{
i = iNew;
}
}
public class PanelB : PanelBase
{
public EventHandler<int> OnChangePanelA = new EventHandler<int>((sender, e) => { }); //stub
string str = "";
public void SetPanelB(string strNew)
{
str = strNew;
}
//PROBLEM HERE HOW TO ACCESS MAIN setPanelACentral
public void ChangePanelA()
{
OnChangePanelA(this, 1000);
}
}