2013-03-26 86 views

回答

1

THX給大家,但我做了簡單的東西.. 希望幫助..

聲明列表:

 List<string> list = new List<string>(); 

在主窗口中:

 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); 
       } 
      }       
     }     
+0

請不要這樣與布爾值...請。 if(String.IsNullOrEmpty(t1.Text.Trim())== false)...只要放一個!否定。如果if(!String.IsNullOrEmpty(t1.Text.Trim()){}。與字符串比較相同... else if(t1.Text.Trim()==「」).... == string.Emtpy – Patrick 2016-03-19 21:12:25

+0

是的,舊的線程,但我在谷歌中發現它,以便其他人:我**強烈建議使用ListBox的數據源來代替它。也就是說,爲它的每一個項目做一個「主列表」,這是你的'list',現在創建第二個'FilteredList',並將匹配項複製到該列表中。在編輯器中,將ListBox綁定到FilteredList。這比**不斷重置項目快得多 - 約15次數在我的測試中。 – 2016-09-19 14:55:38

1

這取決於您的實施。你是否遵循MVVM模式?

如果是,那麼你可以過濾你的文本框設置事件的列表框。在setter中,您可以更改列表框的內容。

<TextBox Text="{Binding SearchText}" /> 
private string _searchText; 
public string SearchText 
{ 
    get { return _searchText; } 
    set 
    { 
     _searchText = value; 
     // Change contents of list box. 
    } 
} 

如果您沒有關注MVVM,那麼您需要在文本框中添加更改事件處理程序。選擇TextBox並在屬性窗口中檢查它的事件。其中有TextChanged事件。添加該事件。無論何時改變文本框文本,這都會給你一個功能。在該功能中,您可以實現用於過濾列表框的邏輯。

+0

是的我已經使用TextChanged事件。 thx – 2013-03-27 04:22:18

+0

然後將此標記爲答案,謝謝, – 2013-03-27 04:54:26