簡體   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