开发者

Winforms: Generic host form for different user controls?

开发者 https://www.devze.com 2023-02-22 20:23 出处:网络
I\'m working on a Winforms project that will have several \"lookup\" style user controls.These controls could be embedded on various forms, but will usually be stand-alone.I\'d like to design a Window

I'm working on a Winforms project that will have several "lookup" style user controls. These controls could be embedded on various forms, but will usually be stand-alone. I'd like to design a Windows form that could host a generic user control and perform several of the tasks common to these lookups. My brain is telling me to do this, but this obviously does not work:

public 开发者_如何学Cpartial class LookupHostForm<TUserControl> : Form where TUserControl : UserControl

Is there a way that I can use one form to host several user controls without the form knowing/caring what the user control is?


The way a form "hosts" a user control is by adding the instance of the user control to the form as a child control. Each form has a public Controls property that exposes a ControlsCollection class. That is a collection of all child controls hosted by that form.

All you have to do is add your user control to the form's Controls collection. This will have exactly the effect that you want. For example:

CustomUserControl uc = new CustomUserControl();
myForm.Controls.Add(uc);

To polish off the effect, you might also want to dock the user control to fill the entire client area of its host form, or anchor it to all four sides. Docking will cause the size of the user control to change when its host form's size changes. Anchoring will just center the user control in the middle of its host. Use the appropriately-named Dock and Anchor properties of your user control to achieve this effect.

And of course, any form object can do this. I would subclass the Form class and expose a strongly-typed method to add instances of my user controls to its controls collection. For example:

public class HostForm : Form
{
    public void SetChildControl<TUserControl>(TUserControl ctrl) where TUserControl : UserControl
    {
        // Add the specified user control to the forms controls collection
        this.Controls.Add(ctrl);

        // Dock the user control in its host form
        ctrl.Dock = DockStyle.Fill;
    }
}


You can certainly do as you need.

Just add a constructor that takes the type or an instance of the UserControl you would like. Then add it as a child control of the form in the constructor. Or add a virtual method that creates the specific control of interest and you have a derived class for each variation you need where each derived class overrides the virtual and returns the correct type. Or have a property that specifies the control. Lots of ways to do it.

0

精彩评论

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

关注公众号