简体   繁体   中英

C# - Find items in ObservableCollection

I'm trying to add a "Search" feature for my Listbox which I've binded to using ObservableCollection but I don't know how I can do that.

For my 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));
        }
    }

I load my Items to the Listbox :

        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;

Now I have a button which enables a TextBox. When the TextBox is enabled and as I type, listBox1 should only show what I typed. If what I typed doesn't exist then the Listbox shouldn't show the items. eg:

在此处输入图片说明

How can I do this and have such a feature? I want it to be like the Windows Phone app search.

Delete Method (using Context Menu):

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

When i click on the delete button, it deletes another item keeping the one I really want to delete.

Consider making use of a CollectionViewSource as your data source instead of using your ObservableCollection directly. You can declare this object as a XAML element or dimension it in code behind. Refresh the view whenever you encounter an appropriate UI event, such as your search box losing focus or a key being pressed, whichever meets your desired UI responsiveness.

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
}

Regarding your deletion code, I would not encourage you to try and line up indices. Try instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM