Here's how you can do it:
using System;
using System.Windows.Forms;
using System.ComponentModel;
public interface IControl : IComponent
{
void DoSomething();
}
public class ControlFactory
{
public static IControl Create(string name)
{
switch (name)
{
case "UserControlA":
var userControlA = new UserControlA();
return userControlA;
case "UserControlB":
var userControlB = new UserControlB();
return userControlB;
}
return null;
}
}
public partial class BaseUserControl : UserControl, IControl
{
public BaseUserControl()
{
InitializeComponent();
}
public virtual void DoSomething()
{
}
}
public partial class UserControlA : BaseUserControl, IControl
{
public UserControlA()
{
InitializeComponent();
}
public override void DoSomething()
{
}
}
public partial class UserControlB : BaseUserControl, IControl
{
public UserControlB()
{
InitializeComponent();
}
public override void DoSomething()
{
}
}
You can save BaseUserControlif you have any functions common to UserControlAand UserControlB; otherwise, eliminate it and make the last two obtained directly from UserControl.
, IControl. , UserControl. .
public interface IControl : IComponent
{
void DoSomething();
Size Size { get; set; }
bool Focus();
event EventHandler FontChanged;
}
Windows Forms - , Control.ControlCollection.Add - Control , . ; , . , :
public interface IControl : IComponent
{
void DoSomething();
Control AsWindowsForms();
}
public partial class BaseUserControl : UserControl, IControl
{
public BaseUserControl()
{
InitializeComponent();
}
public virtual void DoSomething()
{
}
public Control AsWindowsForms()
{
return this as Control;
}
}
:
var controlA = ControlFactory.Create("UserControlA").AsWindowsForms();
var controlB = ControlFactory.Create("UserControlB").AsWindowsForms();
panel1.Controls.Add(controlA);
panel1.Controls.Add(controlB);