wpf 使用文本框过滤列表框项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15627887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
filter listbox items with a textbox
提问by Amine Da.
I have a ListBoxwith some Items, and a TextBox. The text in TextBoxshould match starting characters of Itemsin ListBox& should display filtered result. How to do this?
Thanks.
我有ListBox一些Items,和一个TextBox。文本 inTextBox应匹配Itemsin ListBox& 的起始字符,应显示过滤结果。这该怎么做?谢谢。
采纳答案by Amine Da.
thx to everyone but i made something simpler.. hope that helps ..
谢谢大家,但我做了一些更简单的事情..希望有帮助..
Declare a list:
声明一个列表:
List<string> list = new List<string>();
In the main window:
在主窗口中:
public MainWindow() {
list.Clear();
foreach (String str in lb1.Items)
{
list.Add(str);
}
}
In the textchanged event:
在 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);
}
}
}
回答by NSGaga-mostly-inactive
I love this example from Josh...
我喜欢乔希的这个例子......
http://joshsmithonwpf.wordpress.com/2007/06/12/searching-for-items-in-a-listbox/#
http://joshsmithonwpf.wordpress.com/2007/06/12/searching-for-items-in-a-listbox/#
It's similar approach to the other link - but this one is just brilliant - the shear elegance is good to keep in mind when working with WPF (and how you can get things done in a very simple way).
它与另一个链接的方法类似 - 但这个方法非常棒 - 在使用 WPF 时要记住剪切优雅(以及如何以非常简单的方式完成工作)。
回答by fhnaseer
It depends on your implementation. Are you following MVVM pattern?
这取决于您的实施。您是否遵循 MVVM 模式?
If yes then you can filter your listbox on the set event of your textbox. In the setter you can change contents of your listbox.
如果是,那么您可以根据文本框的设置事件过滤列表框。在 setter 中,您可以更改列表框的内容。
<TextBox Text="{Binding SearchText}" />
private string _searchText;
public string SearchText
{
get { return _searchText; }
set
{
_searchText = value;
// Change contents of list box.
}
}
And if you are not following MVVM then you need to add a change event handler on textbox. Selecte TextBox and check its events in properties window. There is TextChanged event in it. Add that event. This will give you a function whenever textbox text is changed. And in that function you can implement your logic for filtering listbox.
如果您不遵循 MVVM,那么您需要在文本框上添加更改事件处理程序。选择 TextBox 并在属性窗口中检查其事件。其中有 TextChanged 事件。添加该事件。每当文本框文本更改时,这将为您提供一个功能。在该函数中,您可以实现过滤列表框的逻辑。

