自动代码生成C#用户控件

时间:2016-07-08 14:48:03

标签: c# winforms user-controls

我在C#中为DriveComboBox写了一个新组件 (它继承自ImageComboBox - 在互联网上找到的组件),请参阅代码示例:

public class DriveComboBox : ImageComboBox.ImageComboBox
{
    public DriveComboBox()
        : base()
    {
        foreach (ImageComboBoxItem item in allImageComboBoxItems)
        {
           this.Items.Add(item);                
        }
    }
}

此部分代码将驱动器添加到控件中,并在将此控件拖入表单后,将项目添加到表单代码的设计器中。 问题是,一旦程序运行,上面的代码添加了项目,然后设计师代码再次添加它们,所以我们最终得到了双重项目。

问题是添加项目的位置应该放在控件中,或者如何防止设计师再次添加它们?

1 个答案:

答案 0 :(得分:0)

我有同样的问题,似乎" visual ??" visual studio的设计者可以使用运行时代码作为设计时代码。 我不明白完成了什么,但我确实设法避免了这个方法的问题:

Cannot convert the "System.Runtime.InteropServices.COMException (0xC004F025)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32      errorCode, IntPtr errorInfo)
   at System.Management.ManagementObject.InvokeMethod(String methodName, ManagementBaseObject inParameters, 
InvokeMethodOptions options)
   at System.Management.Automation.ManagementObjectAdapter.InvokeManagementMethod(ManagementObject obj, String 
methodName, ManagementBaseObject inParams)" value of type    "System.Management.Automation.ErrorRecord" to type 
"System.Management.ManagementException".
At line:3 char:1
+ [System.Management.ManagementException] $_
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException

我这样使用:

protected bool IsInDesignMode
{
    get { return DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime; }
}