AutoCompleteStringCollection,每个字符串都带有标签

时间:2014-01-28 08:31:38

标签: c# .net winforms

是否可以在AutoCompleteStringCollection附加Tag中输入字符串?因为我在研究中找不到本地方式,我试图自己实现它。但现在的问题是,当用户点击AutoCompleteStringCollection中的条目时,它似乎不会触发其他事件,例如在TextBox中。

  1. 本机可以这样做吗?
  2. 如果没有,我怎么知道用户点击了哪个索引,以便我可以判断输入是手动输入(TextChanged - 事件)还是选择(?? - 事件)?

1 个答案:

答案 0 :(得分: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);
    }
}