2009-04-08 123 views
0

首先代碼(對不起,如果它不是100%)我不是專家,然後問題如下。保留列表框項目選擇

public partial class Window1 : Window 
    { 
    CollectionView cv; 

    public Window1() 
    { 
     InitializeComponent(); 

     List<Person> ppl = new List<Person>(); 
     BitmapImage b = new BitmapImage(new Uri(@"http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png",UriKind.Absolute)); 
     ppl.Add(new Person(b, "world1")); 
     ppl.Add(new Person(b, "world2")); 
     ppl.Add(new Person(b, "world3")); 
     ppl.Add(new Person(b, "world4")); 
     ppl.Add(new Person(b, "world5")); 
     ppl.Add(new Person(b, "world6")); 

     lb.ItemsSource = ppl; 
     lb.SelectedIndex = 1; 

     cv = (CollectionView)CollectionViewSource.GetDefaultView(lb.ItemsSource); 

     new TextSearchFilter(cv, textBox1); 
    } 
} 

public class TextSearchFilter 
{ 
    public TextSearchFilter(CollectionView cv, TextBox tb) 
    { 
     string filterText = ""; 

     cv.Filter = delegate(object obj) 
     { 
      Person p = obj as Person; 
      int index = p.Info.IndexOf(filterText,0,StringComparison.InvariantCultureIgnoreCase); 
      return index > -1; 
     }; 

     tb.TextChanged += delegate 
     { 
      filterText = tb.Text; 
      cv.Refresh(); 
     }; 
    } 
} 

    class Person 
    { 
     private BitmapImage myImage; 
     private string myInfo = ""; 

     public BitmapImage Image 
     { 
      get { return myImage; } 
      set { myImage = value; } 
     } 

     public string Info 
     { 
      get { return myInfo; } 
      set { myInfo = value; } 
     } 

     public Person(BitmapImage Image, string Info) 
     { 
      this.Image = Image; 
      this.Info = Info; 
     } 
    } 

謝謝您的閱讀,因爲你會被明白現在是代碼過濾基於在文本框中輸入,這BTW就像一個魅力列表框。

我的問題是如何在過濾期間保留選擇。當窗口加載時,列表框中包含所有項目,我選擇第一個項目,然後在文本框中鍵入內容,並且列表框過濾器僅顯示相關項目,選擇另一個項目後,我將所有文本從文本中移除使其回到原始狀態,但是這次選擇已經改變爲僅在過濾視圖中選擇的項目(因此,不是所顯示的兩個項目作爲選擇被顯示,只有一個顯示爲選擇)。這種行爲很明顯,因爲我正在過濾一個集合,所以集合更改選擇的時刻就會丟失。

有沒有辦法保留選擇?任何指針?

很多謝謝。

回答

1

可能在你TextChanged事件處理程序,你應該存儲ListBox的選擇項,像這樣:

Person[] selectedPeople = new Person[lb.SelectedItems.Count]; 
lb.SelectedItems.CopyTo(selectedPeople, 0); 

然後刷新後過濾,加入他們回用:

foreach (Person p in selectedPeople) 
{ 
    if(lb.Items.Contains(p)) 
    { 
     lb.SelectedItems.Add(p); 
    } 
} 

我之所以有它使用CopyTo從和陣列中的節約只是用代替:

IList selectedPeople = lb.SelectedItems; 

是後者會保持對lb.SelectedItems的引用,並且foreach會修改枚舉,導致引發異常。可能有一個更簡單的方法,但這應該讓你朝着正確的方向前進。