C#MDI事件帮助

时间:2009-05-31 19:44:17

标签: c# events mdi

我有一个MDI容器的表单。在该表格中,我生成6个子表单,每个表单都带有标签:

for (int i = 0; i < 6; i++)
{
    Form window = new Form();
    window.Width = 100;
    window.Height = 100;

    window.MdiParent = this;
    window.FormBorderStyle = FormBorderStyle.FixedToolWindow;

    Label label = new Label();
    label.AutoSize = true;
    label.Location = new System.Drawing.Point(1, 1);
    label.Size = new System.Drawing.Size(35, 13);
    label.TabIndex = 1;
    label.Name = "label" + i.ToString();
    label.Text = window.Top.ToString();

    window.LocationChanged += new System.EventHandler(HERE);

    window.Controls.Add(label);
    window.Show();              
}

我在windowchanged的locationchanged上添加了一个事件。现在该如何做到标签更新到窗口位置?

2 个答案:

答案 0 :(得分:1)

我认为这条线可以帮到你:

window.LocationChanged += new EventHandler(delegate(object o, EventArgs evtArgs) { 
    label.Text = window.Location.ToString(); 
});

答案 1 :(得分:0)

嗯,最简单的方法是使用lambda表达式或匿名方法:

window.LocationChanged += (sender, args) => label.Text = window.Top.ToString();

如果你使用C#1.1,你需要有点棘手,因为标签是在C#2+中自动捕获的 - 你必须创建一个这样的新类:

internal class LocationChangeNotifier
{
    private readonly Label label;

    internal LocationChangeNotifier(Label label)
    {
        this.label = label;
    }

    internal void HandleLocationUpdate(object sender, EventArgs e)
    {
        label.Text = ((Control) sender).Top.ToString();
    }
}

然后将其用作:

LocationChangeNotifier notifier = new LocationChangeNotifier(label);
window.LocationChanged += new EventHandler(notifier.HandleLocationUpdate);

捕获的变量不是很好吗? :)