开发者

Removing ListBoxItems from a bounded ListBox in WPF?

开发者 https://www.devze.com 2023-02-12 15:43 出处:网络
I have a ListBox that has items that can be dragged and dropped onto a StackPanel. When these items are dropped, I need them to be removed from the ListBox, which is bound to a list.

I have a ListBox that has items that can be dragged and dropped onto a StackPanel. When these items are dropped, I need them to be removed from the ListBox, which is bound to a list.

The item that is beign dropped, and should be removed as an example would be a Person.

public class Person()
{
    private int Age {get;set;}
    private string Name {get;set;}

    public Person(){...}

    /*Getter and Setter Methods to follow*/
}

Note This class is completely arbitrary, and just used as an example.

This 开发者_StackOverflow中文版class will be bound to a ListBox using the following code. The call to get the list of Person objects, is also not implementation specific.

List<Person> personList = PersonDAO.getAll();
listBox.ItemsSource = personList;
listBox.DisplayMemberPath = "Name";

Everything works fine in my application so far, except for removing items from the list.

When an item is dropped, it needs to be removed from the list. How is the proper way to remove the dragged item from the ListBox without removing it from the source?


Don't think in terms of removing items from a ListBox. Think in terms of removing items from the collection that the ItemsSource of the ListBox is bound to. This lets you avoid writing all kinds of ugly, unwieldy code.

It sounds like you're reluctant to modify the underlying collection of Person objects. OK. So create a new one, one that's not "all the Person objects" but rather "all the Person objects still present in the ListBox."


Use an ObservableCollection<Person> or another collection implementing INotifyCollectionChanged as here: http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx


The easiest way is to filter the person list, like so:

List<Person> personList = PersonDAO.getAll();
listBox.ItemsSource = personList;
listBox.DisplayMemberPath = "Name";
personListView = (CollectionView)
    CollectionViewSource.GetDefaultView(personList);
personListView.Filter += (item) => { someCriteriaForInclusion };

When a drag occurs call personListView.Refresh() to reapply the filter.

0

精彩评论

暂无评论...
验证码 换一张
取 消