简体   繁体   中英

Listbox refreshing and binding wp7

I actually display on my Listbox this list of item that i retrive from XML . When I click on an Item i am going back to the same method and creating a new list to display with different items.

I am wondering why it's not clearing the previous list.

This is the code I use, I can't figure this out ..

if (e.Error == null)
        {
            // Retrieving the subfolders
            XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
            XNamespace aNamespace = XNamespace.Get("http://schemas.datacontract.org/2004/07/System.IO");

            var folders = from query in xdoc.Descendants(aNamespace.GetName("DirectoryInfo"))
                          select new Folder
                          {
                              Name = (string)query.Element("OriginalPath"),
                          };

            ObservableCollection<Folder> LFolders = new ObservableCollection<Folder>();

            foreach (Folder f in folders)
            {
                LFolders.Add(f);
            }

            listBox1.ItemsSource = LFolders;
            listBox1.SelectionChanged += new SelectionChangedEventHandler(listBox1_SelectionChanged);
        }

Two suggestions:

  1. Consider using the MVVM pattern and then storing and updating your ObservableCollection on the view model instead.
  2. Set the SelectionChanged event in XAML instead of where you're setting it now. For every call to this method you're appending an additional event handler to your listBox1.

If you set the Itemssource to null before you set the new value, I believe that will work. Also, you can try making LFolders a class variable. When you begin the method, clear the collection and then add to it. THe observable collection that is bound to the listbox will take care of updating the listbox.

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