如何访问容器'来自用户控制的事件?

时间:2014-01-03 18:41:01

标签: c# winforms

我需要从我的用户控件(AdvancedButton)中提升父母的 SizeChange 事件。如果容器的大小将被更改,我需要更改我的用户控件的大小。但我不知道如何我可以访问容器的事件。我试过这种方式:

public AdvancedButton()
    {            
        Form1 frm = (Form1)this.FindForm();
        frm.SizeChanged += OnFormSizeChanged;

        DoubleBuffered = true;
        MouseDown += OnMouseDown;
        MouseUp += OnMouseUp;
        MouseMove += OnMouseMove;
        Click += OnClick;
    }

    private void OnFormSizeChanged(object sender, EventArgs e)
    {
        this.Width += this.Width - 1;
        this.Height += this.Height - 1;
    }

但是当我尝试启动应用程序时,这种方式不起作用。有错误的文本: Kyrsovoi.exe中发生未处理的“System.NullReferenceException”类型异常

我找到了一种有效但不是我需要的方式,因为在这里我们必须在Form1.Designer.cs中编写 FindForm()

private void InitializeComponent()
    {
        ...
        this.AdvancedButton1 = new WindowFormsApplication1.AdvancedButton(FindForm());
        ...
    }

MyButton.cs代码:

public AdvancedButton(Form parent)
    {
        parent.SizeChanged += OnFormSizeChanged;
        DoubleBuffered = true;
        MouseDown += OnMouseDown;
        MouseUp += OnMouseUp;
        MouseMove += OnMouseMove;
        Click += OnClick;
    }

    private void OnFormSizeChanged(object sender, EventArgs e)
    {
        this.Width += this.Width - 1;
        this.Height += this.Height - 1;
    }

请帮助。也许有人知道解决这个任务的方法。

1 个答案:

答案 0 :(得分:0)

您应该将父事件相关代码移动到OnParentChanged:

protected override void OnParentChanged(EventArgs e)
{
    base.OnParentChanged(e);

    if (this.Parent != null)
    {
        this.Parent.SizeChanged += OnFormSizeChanged; // this.ParentForm.SizeChanged += ...
    }
}

void OnFormSizeChanged(object sender, EventArgs e)
{
    // ...
}

考虑使用Anchor / Dock / Margin属性进行布局。