开发者

Creating a custom Panel class C#

开发者 https://www.devze.com 2023-02-25 19:07 出处:网络
Hey guys, I\'m trying to set up a custom Panel called FormPanel from Panel class FormPanel : Panel { bool previous;

Hey guys, I'm trying to set up a custom Panel called FormPanel from Panel

class FormPanel : Panel
    {
        bool previous;
        FormPanel l;

        public FormPanel()
        {
            previous = false;
            l.Parent = this;
            l.Dock = DockStyle.Fill;

        }
    }

This is pretty much where I am right now. I want the FormPanel to have a bool var and want to set it's default properties of Parent and Dock. How does 开发者_开发技巧this work? How can I set those?


In case you want your panel to have DockStyle.Fill as default for the Dock property, do this:

public class FormPanel : Panel
{
    public FormPanel()
    {
        this.Dock = DockStyle.Fill;
    }

    [System.ComponentModel.DefaultValue(typeof(DockStyle), "Fill")]
    public override DockStyle Dock
    {
        get { return base.Dock; }
        set { base.Dock = value; }
    }
}

This makes the Dock property default to Fill within the property window.


You shouldn't use an internal variable of your type, instead set the properties (that you inherit from the baseclass) directly:

class FormPanel : Panel
{
    bool previous;

    public FormPanel()
    {
        previous = false;
        base.Parent = this;
        base.Dock = DockStyle.Fill;

    }
}

although I don't think that "base.Parent=this" will work ...


You need to add more info about what you're trying to achieve.

As it stands your FormPanel has a private field (l) which is itself a FormPanel:

  FormPanel l;

You never instantiate this field, so it will always be null, and the assignments to properties in the constructor will fail with a NullReferenceException:

l.Parent = this;              
l.Dock = DockStyle.Fill;

If you did instantiate this private field, you would have recursion, since your FormPanel contains a private FormPanel, which itself contains a private FormPanel, ...

l = new FormPanel();
l.Parent = this;              
l.Dock = DockStyle.Fill;

You say you want to set a default Parent, but I don't see how a FormPanel can know what it's parent is in the constructor, unless you pass the parent as a parameter to the constructor, e.g. maybe you're looking for something like:

public FormPanel() : this(null)
{
}

public FormPanel(Control parent)
{
    if (parent != null)
    {
        this.Parent = parent;
    }
    this.Dock = DockStyle.Fill;
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消