繁体   English   中英

在Load和数组为空之前加载C#自定义控件属性

[英]C# Custom Control Properties load before Load and arrays are empties

为更好的理解而编辑

我做了一些具有全局变量的自定义控件。

private string[] LBTitles = new string[1] { "Rien" };
//...
[CategoryAttribute("WildData"), DescriptionAttribute("Tableau des noms des titres au dessus de le listbox")]
public string[] Titles
{
    get { return LBTitles; }

    set { LBTitles = value; OnColumns(EventArgs.Empty); }
}

OnColums做很多事情来格式化控件。 其中之一是:

int vLongest = 0;
//...
//Si le plus long est plus petit que le titre de la colonne
if (vLongest < LBTitles[i].Length)
{
    vLongest = LBTitles[i].Length;
}

以上是我自己控制的。 一切正常,美好的一天,等等。

现在,将其添加到表单中:-添加完毕,一切正常-通过设计修改属性,一切正常-我尝试运行它...这是问题。

构建时,它将以下代码添加到InitializeComponent()中:

this.wildList1 = new WildList.WildList();
//Which is ok but also it add, everytime I build, this:
            // 
            // wildList1
            // 
            this.wildList1.Colors = new string[] {
        null};
            this.wildList1.Font = new System.Drawing.Font("Courier New", 8F);
            this.wildList1.Location = new System.Drawing.Point(211, 33);
            this.wildList1.Name = "wildList1";
            this.wildList1.Positions = new int[] {
        0};
            this.wildList1.Size = new System.Drawing.Size(238, 224);
            this.wildList1.TabIndex = 16;
            this.wildList1.Titles = new string[] {
        null};

它添加了几行代码来重置我的数组。 为什么? 我怎么能骑他们呢? 或者至少让它们使用程序员(又名我)输入到设计器中的值?

因为当它经过重置它的行时,它还会调用属性“ set”,该属性将调用OnColumns,然后尝试对空数组进行处理,这会导致崩溃。

您应该在控件的构造函数中填充数组。

如果要查看设置属性的确切顺序,请查看表单的InitializeComponent方法。

好的,我想出了问题所在。 它来自Form1.Designer.cs

在InitializeComponent()中,它执行

this.wildList1 = new WildList.WildList();

一切都很好,但是下面几行显示了:

// 
            // wildList1
            // 
            this.wildList1.Colors = new string[] {
        null};
            this.wildList1.Name = "wildList1";
        this.wildList1.Font = new System.Drawing.Font("Courier New", 8F);
        this.wildList1.Location = new System.Drawing.Point(190, 64);
        this.wildList1.Name = "wildList1";
        this.wildList1.Positions = new int[] {
    0};
        this.wildList1.Size = new System.Drawing.Size(238, 224);
        this.wildList1.TabIndex = 16;
        this.wildList1.Titles = new string[] {
    null};

等等...这将使用现在为空的数组调用属性“ Colors”的“ set”,并调用函数。

为什么它会自动添加代码以重置全局变量? 有没有办法防止自动添加此代码?

如果我对您的理解正确,那么您具有不应更改的属性,因为它们在内部用作某种const替代项? 如果是这样,请使用DesignerSerializationVisibilityAttribute对其进行标记

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int[] MyArrayProperty
{
    get 
    {
        // get here
    }       
}

void SetMyArrayProperty(int[] a)
{
    // set here
}

这将它们隐藏在设计器中,并防止覆盖它们。 请注意,删除属性的set部分还可以防止设计器和属性窗口也更改该值。

我发现了问题。

这是由于引用了控件的dll。 它使用的是“缓存的”,或者当我第一次测试控件时(它有错误),我不知道控件的版本,即使我正在更改它使用的.dll文件也是如此。 因此,我完全删除了引用,并使用未经调试的dll版本制作了一个新引用,现在一切正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM