我有一个mdi,我有几行代码,如下所示。只有chage才是正在打开的Form对象。因此,我希望所有这些工作仅使用单一功能定义。 当我试图捕获发件人时,它在这里给我ToolStipMenuItem。但是我希望它的发件人是表单名称,以便我可以打开相应的表单。
private void purchaseInvoiceToolStripMenuItem_Click(object sender, EventArgs e)
{
Forms.PurchaseInvoice purinv = new DigitalInvy.Forms.PurchaseInvoice();
purinv.Show();
}
private void lederGroupsToolStripMenuItem_Click(object sender, EventArgs e)
{
Forms.LedgerGroup lgrp = new DigitalInvy.Forms.LedgerGroup();
lgrp.Show();
}
private void voucherEntryToolStripMenuItem_Click(object sender, EventArgs e)
{
Forms.VoucherEntry ventry = new DigitalInvy.Forms.VoucherEntry();
ventry.Show();
}
private void currencyToolStripMenuItem_Click(object sender, EventArgs e)
{
Forms.CurrencyMaster currency = new DigitalInvy.Forms.CurrencyMaster();
currency.Show();
}
private void countryToolStripMenuItem_Click(object sender, EventArgs e)
{
Forms.CountryMaster country = new DigitalInvy.Forms.CountryMaster();
country.Show();
}
我想做这样的事情
private void cMenuItem_Click(object sender, EventArgs e)
{
if(sender.GetType()==Form)
{
Forms.CountryMaster country = new DigitalInvy.Forms.CountryMaster();
country.Show();
}
}
答案 0 :(得分:2)
这个怎么样?如果你的某些表单需要构造函数参数,它会让生活变得有点棘手,但你可能会有一个非泛型的重载,需要Func<Form>
来说明如何构建要显示的表单。
private static void AssociateBuilder<T>(ToolStripMenuItem item)
where T : Form, new()
{
item.Click += () => new T().Show();
}
AssociateBuilder<PurchaseInvoice>(purchaseInvoiceToolsStripMenuItem);
AssociateBuilder<Ledger>(ledgerGroupsToolStripMenuItem);
// etc
答案 1 :(得分:1)
您正在获取所有这些小型Click事件处理程序,因为您使用了设计器来创建事件处理程序。如果您自己编写事件分配,很容易摆脱它们。例如:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
purchaseInvoiceToolStripMenuItem.Click += (o,e) => createChild(new frmPurchaseInvoice());
ledgerGroupToolStripMenuItem.Click += (o, e) => createChild(new frmLedgerGroup());
// etc..
}
private void createChild(Form frm) {
frm.MdiParent = this;
frm.Show();
}
}
如果您仍然使用C#2.0,则可以使用匿名方法:
purchaseInvoiceToolStripMenuItem.Click += delegate { createChild(new frmPurchaseInvoice()); };