2014-01-15 45 views
0

幫助! 我想做一個自定義的ListBox控件,可以用來從中選擇一個DashStyle。問題是,當我將自定義組件拖動到我的窗體時,它會添加項目(這是可以的),但是當我運行程序時,它會再次添加項目,給我重複項目。 這裏是我的代碼:CustomListBox重複項目

namespace Help 
{ 
    public partial class LineStyleListBox : ListBox 
    { 
     private Pen[] pens; 
     string[] styleNames; 
     public LineStyleListBox() 
     { 
      InitializeComponent();    
      styleNames = System.Enum.GetNames(typeof(DashStyle)); 
      pens = new Pen[styleNames.Length]; 
      for (int i = 0; i != pens.Length; i++) 
      { 
       pens[i] = new Pen(new SolidBrush(Color.Black), 1); 
       pens[i].DashStyle = (DashStyle)i; 
      }       
      Items.AddRange(styleNames);   
     } 
    } 
} 

我希望得到任何幫助,或評論。謝謝!

+1

可能只是檢查項目是否爲空? if(Items.Count <= 0)Items.AddRange(styleNames); –

回答

0

我能夠這樣做是爲了避開 -

if(LicenseManager.UsageMode == LicenseUsageMode.Designtime) 
      Items.AddRange(styleNames);  

不知怎的,它仍然顯示的項目時,我的控件添加到我的形式。 有人可以解釋爲什麼嗎?如果有更好的方法。由於

+0

我認爲你錯了。如果只希望在非設計時模式下使用控件時才添加項目。然後代碼應該是:'if(LicenseManager.UsageMode!= LicenseUsageMode.Designtime){Items.AddRange(styleNames); }(注意不相等的比較)。提示:你應該更新你的問題,而不是發佈自己問題的答案。 – IronGeek

0

嘗試改變控制的構造是這樣的:

public LineStyleListBox() 
{ 
    InitializeComponent();  

    // do not add items if the control is in design mode 
    if (LicenseManager.UsageMode == LicenseUsageMode.Designtime) 
    return; 

    styleNames = System.Enum.GetNames(typeof(DashStyle)); 
    pens = new Pen[styleNames.Length]; 
    for (int i = 0; i != pens.Length; i++) 
    { 
    pens[i] = new Pen(new SolidBrush(Color.Black), 1); 
    pens[i].DashStyle = (DashStyle)i; 
    }       

    Items.AddRange(styleNames);   
} 
0

VS設計師序列化的項目。當應用程序啓動在第一個LineStyleListBox構造函數和第二個 - 在Form的InitializeComponent()中添加的樣式時。

如果你想看到在德興時間的樣式,不希望有任何新的風格

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] 
public new ListBox.ObjectCollection Items 
{ 
    get { return base.Items; } 
} 
0

一個簡單的方法是使用一個bool hasAdded;,並將其設置爲true,一旦你已經添加項目,在添加更多內容之前檢查它。

希望這可以幫助別人!