使用文本框过滤列表框项

我有一个包含一些ItemsListBox和一个TextBoxTextBox中的TextBox应匹配ListBoxItems起始字符,并应显示筛选结果。 这该怎么做? 谢谢。

我喜欢Josh的这个例子……

http://joshsmithonwpf.wordpress.com/2007/06/12/searching-for-items-in-a-listbox/#

它与其他链接的方法类似 – 但是这个方法非常出色 – 在使用WPF时要记住剪切优雅(以及如何以非常简单的方式完成工作)。

这取决于您的实施。 你在关注MVVM模式吗?

如果是,那么您可以在文本框的set事件中过滤列表框。 在setter中,您可以更改列表框的内容。

  private string _searchText; public string SearchText { get { return _searchText; } set { _searchText = value; // Change contents of list box. } } 

如果您不关注MVVM,则需要在文本框上添加更改事件处理程序。 选择TextBox并在属性窗口中检查其事件。 其中有TextChanged事件。 添加该事件。 每当更改文本框文本时,这将为您提供一个function。 在该function中,您可以实现过滤列表框的逻辑。

thx to everyone但我做的更简单..希望有帮助..

声明一个列表:

  List list = new List(); 

在主窗口中:

  public MainWindow() { list.Clear(); foreach (String str in lb1.Items) { list.Add(str); } } 

在textchanged事件中:

  public void t1_TextChanged(object sender, TextChangedEventArgs e) { if (String.IsNullOrEmpty(t1.Text.Trim()) == false) { lb1.Items.Clear(); foreach (string str in list) { if (str.StartsWith(t1.Text.Trim())) { lb1.Items.Add(str); } } } else if(t1.Text.Trim() == "") { lb1.Items.Clear(); foreach (string str in list) { lb1.Items.Add(str); } } }