2014-01-28 34 views
3

是否可以在AutoCompleteStringCollection附加的Tag字符串條目?因爲在我的研究中找不到原生的方式,所以我試圖自己實現它。但現在的問題是,當用戶點擊AutoCompleteStringCollection中的一個條目時,似乎並沒有發起額外的事件,例如在TextBox中說過。AutoCompleteStringCollection帶有每個字符串的標籤

  1. 原生可以這樣做嗎?
  2. 如果不是,我怎麼知道用戶點擊了哪個索引,以便我可以判斷輸入是手動輸入(TextChanged -Event)還是選擇(?? - event)?
+0

您可以通過檢查其集合的元素'如果(AutoComplStrCol.Contains(TextBox1.Text))' – SysDragon

+0

是啊,我已經這樣做了。但它似乎是一個不好的解決方案,因爲它的1.慢和2.這不能保證正確的功能,當收集中有兩個相同的字符串。 –

回答

1

由於似乎沒有其他解決方案,我已經實現了我自己的解決方案。 如果需要,請使用此功能。您可以使用TextChanged-TextBoxComboBox的事件來使用GetTag擴展方法獲取值。

public class TaggedAutoCompleteStringCollection : AutoCompleteStringCollection 
{ 
    private List<object> _tags; 

    public TaggedAutoCompleteStringCollection() 
     : base() 
    { 
     _tags = new List<object>(); 
    } 

    public int Add(string value, object tag) 
    { 
     int result = this.Add(value); 
     _tags.Add(tag); 

     return result; 
    } 

    public void AddRange(string[] value, object[] tag) 
    { 
     base.AddRange(value); 
     _tags.AddRange(tag); 
    } 

    public new void Clear() 
    { 
     base.Clear(); 
     _tags.Clear(); 
    } 

    public bool ContainsTag(object tag) 
    { 
     return _tags.Contains(tag); 
    } 

    public int IndexOfTag(object tag) 
    { 
     return _tags.IndexOf(tag); 
    } 

    public void Insert(int index, string value, object tag) 
    { 
     base.Insert(index, value); 
     _tags.Insert(index, tag); 
    } 

    public new void Remove(string value) 
    { 
     int index = this.IndexOf(value); 

     if (index != -1) 
     { 
      base.RemoveAt(index); 
      _tags.RemoveAt(index); 
     } 
    } 

    public new void RemoveAt(int index) 
    { 
     base.RemoveAt(index); 
     _tags.RemoveAt(index); 
    } 

    public object TagOfString(string value) 
    { 
     int index = base.IndexOf(value); 

     if (index == -1) 
     { 
      return null; 
     } 

     return _tags[index]; 
    } 
} 

public static class TaggedAutoCompleteStringCollectionHelper 
{ 
    public static object GetTag(this TextBox control) 
    { 
     var source = control.AutoCompleteCustomSource as TaggedAutoCompleteStringCollection; 

     if (source == null) 
     { 
      return null; 
     } 

     return source.TagOfString(control.Text); 
    } 

    public static object GetTag(this ComboBox control) 
    { 
     var source = control.DataSource as TaggedAutoCompleteStringCollection; 

     if (source == null) 
     { 
      return null; 
     } 

     return source.TagOfString(control.Text); 
    } 
}