2015-01-02 2 views
0

에서 항목 찾기하지만 난 그렇게 할 수있는 방법을 모르겠어요. 내 ObservableCollection에를 들어C#을 - 내가 <strong>ObservableCollection에</strong>를 사용하여 바인더 제본 한 내 <strong>목록 상자</strong>에 대한 <strong>"검색"</strong> 기능을 추가하기 위해 노력하고있어 ObservableCollection에

:

ObservableCollection<ItemProperties> ItemCollection { get; set; } 
public class ItemProperties : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 
     public ItemProperties() { } 

     private string m_ID; 
     public string ID 
     { 
      get { return m_ID; } 
      set 
      { 
       m_ID = value; 
       OnPropertyChanged("ID"); 
      } 
     } 

     private string m_Title; 
     public string Title 
     { 
      get { return m_Title; } 
      set 
      { 
       m_Title = value; 
       OnPropertyChanged("Title"); 
      } 
     } 

     protected void OnPropertyChanged(string name) 
     { 
      PropertyChangedEventHandler handler = this.PropertyChanged; 
      if (handler != null) 
       handler(this, new PropertyChangedEventArgs(name)); 
     } 
    } 

나는 목록 상자 내 항목을로드 :

 string[] fileNames = isf.GetDirectoryNames("Files/*.*"); 
     ItemCollection = new ObservableCollection<ItemProperties>(); 
     foreach (var Directory in fileNames) 
     { 
      // code which reads and loads the text files to string which then is added to the Collection 
     } 
     ItemCollection.Add(new ItemProperties { ID = a_ID, Title = a_Title}); 
     IEnumerable<ItemProperties> query = ItemCollection.OrderBy(Dat => Dat.Title); 
     listBox1.ItemsSource = query; 

는 지금은 텍스트 상자를 할 수있는 버튼이 있습니다. TextBox가 활성화되어 있고 입력 할 때 listBox1은 입력 한 내용 만 표시해야합니다. 입력 한 내용이 존재하지 않으면 목록 상자에 항목이 표시되지 않아야합니다. 예컨대 :

enter image description here

어떻게 이렇게 그와 같은 기능을 할 수 있습니까? Windows Phone 앱 검색과 같아야합니다. (상황에 맞는 메뉴를 사용하여)

삭제 방법 : 내가 삭제 버튼을 클릭하면

var contextMenuOpenedIndex = listBox1.Items.IndexOf((sender as MenuItem).DataContext); 
ItemCollection.RemoveAt(contextMenuOpenedIndex); 

, 내가 정말 삭제하려는 하나를 유지하는 다른 항목을 삭제합니다.

+0

내 머리 꼭대기에서 벗어나는 'TextBox'는 사용자가 입력 할 때마다 발생하는 '변경됨'이벤트와 유사합니다. 거기에 상자에 들어있는 내용으로 전체 목록을 필터링 할 수 있습니다. 입력 할 때 변경해야합니다. – Omada

답변

1

ObservableCollection을 직접 사용하는 대신 데이터 소스로 CollectionViewSource을 사용하는 것을 고려하십시오. 이 개체를 XAML 요소로 선언하거나 코드 뒤에 차원을 지정할 수 있습니다. 검색 상자의 포커스 또는 키 누름 중 원하는 UI 응답을 충족시키는 적절한 UI 이벤트가 발생할 때마다보기를 새로 고칩니다.

private CollectionViewSource MySource { get; set; } 

private void PopulateView() 
{ 
    string[] fileNames = isf.GetDirectoryNames("Files/*.*"); 
    ItemCollection = new ObservableCollection<ItemProperties>(); 
    foreach (var Directory in fileNames) 
    { 
     // code which reads and loads the text files to string which then is added to the Collection 
    } 
    ItemCollection.Add(new ItemProperties { ID = a_ID, Title = a_Title}); 

    // Create view 
    MySource = new CollectionViewSource { 
     Source = ItemCollection 
    }; 

    // Add sorting support 
    MySource.View.SortDescriptions.Add(new SortDescription("Title", ListSortDirection.Ascending)); 

    // Create a filter method 
    MySource.View.Filter = obj => 
    { 
     var item = obj as ItemProperties; 

     // Predicate to determine if search box criteria met; change as needed 
     return item.Title.Contains(txtMyFilter.Text); 
    } 

    // Initialize selected item to avoid SelectionChanged event 
    MySource.View.MoveCurrentToFirst() 

    // Set as ListBox source 
    listBox1.ItemsSource = MySource.View; 
} 

// Bind to XAML TextBox element's KeyUp event or similar 
private void OnFilterKeyUp(object sender, KeyEventArgs e) 
{ 
    MySource.View.Refresh(); 

    // Include any other display logic here, such as possibly scrolling to top of ListBox 
} 

삭제 코드와 관련해서는 색인을 작성하지 않는 것이 좋습니다. 대신 시도해보십시오 :

ItemCollection.Remove((sender as MenuItem).DataContext as ItemProperties); 
+0

이유는 무엇입니까? 'System.Windows.Data.CollectionViewSource'형식을 'System.Collections.IEnumerable'형식으로 암시 적으로 변환 할 수 없습니다. 명시 적 변환이 존재합니다 (캐스트가 누락 되었습니까?) listBox1.ItemsSource = Mysource? – Zer0

+0

@ F4z 죄송합니다. 'listBox1.ItemsSource = MySource.View'이어야합니다. 그 사실을 반영하기 위해 답을 업데이트했습니다. 이 속성은 [IEnumerable]과 [ INotifyCollectionChanged'입니다. – lsuarez

+0

필터! 그건 좋은 일이지만 두 가지 문제가 있습니다. 첫 번째 문제는 내가 quey를 검색하면 나타나고 그 항목을 삭제할 수 없다는 것입니다. 다른 문제는 어떤 이유로 페이지가로드 될 때 listBox1_SelectionChanged 이벤트가 트리거된다는 것입니다. 내 삭제 방법을 보여주는 조금 대답을 업데이 트했습니다. – Zer0

관련 문제