我尝试使用ControlDesigner创建自定义控件。我找到了一种在http://code.msdn.microsoft.com/WinFormsCustomCtrl使用带有ClientProfile的ControlDesinger的方法,但是要使用这个方法,想要使用的项目必须手动添加Control的Design-Project dll。
是否可以将Design-Project dll作为嵌入式资源添加到我的控件中,或者是否有办法自动将Design-Project dll添加到想要使用我的控件的项目中?
项目控制:
namespace NControl
{
[Designer("NDesign.MyControlDesigner, NDesign")]
public class MyControl : Control
{
static MyControl()
{
TypeDescriptor.AddProvider(new DynamicDesignerProvider(TypeDescriptor.GetProvider(typeof(object))), typeof(object));
}
}
//###########################################################################################
//########################### Dynamic Design Provider from MSDN ##############################
//###########################################################################################
internal sealed class DynamicDesignerProvider : TypeDescriptionProvider
{
internal DynamicDesignerProvider(TypeDescriptionProvider parent) : base(parent) { }
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
if (objectType.Assembly == typeof(MyControl).Assembly)
{
IComponent component = instance as IComponent;
if (component != null && component.Site != null)
{
return new DesignerAttributeTypeDescriptor(base.GetTypeDescriptor(objectType, instance), component);
}
}
return base.GetTypeDescriptor(objectType, instance);
}
}
internal sealed class DesignerAttributeTypeDescriptor : CustomTypeDescriptor
{
IServiceProvider _provider;
internal DesignerAttributeTypeDescriptor(ICustomTypeDescriptor parent, IComponent component)
: base(parent)
{
if (component != null)
{
_provider = component.Site;
}
}
public override AttributeCollection GetAttributes()
{
AttributeCollection ac = base.GetAttributes();
List<Attribute> attrs = new List<Attribute>();
foreach (Attribute attr in ac)
{
DesignerAttribute dattr = attr as DesignerAttribute;
if (dattr != null && dattr.DesignerBaseTypeName.StartsWith("System.ComponentModel.Design.IDesigner"))
{
ITypeResolutionService trs = null;
if (_provider != null)
{
trs = (ITypeResolutionService)_provider.GetService(typeof(ITypeResolutionService));
}
if (trs != null && trs.GetType(dattr.DesignerTypeName) == null)
{
DesignerAttribute da = new DesignerAttribute("System.Windows.Forms.Design.ControlDesigner, System.Design");
attrs.Add(da);
continue;
}
}
attrs.Add(attr);
}
return new AttributeCollection(attrs.ToArray());
}
}
}
项目设计:
namespace NDesign
{
public class MyControlDesigner : ParentControlDesigner
{
// My DesignCode
}
}