2017-07-15 69 views
-1

當程序運行時,它從XML文件填充listBox(lstBox)。 然後我有代碼來刪除XML文件中的元素或聯繫人,我也想從我的列表框中刪除該條目。當我嘗試通過lstBox.Items.Clear()或RemoveAt刪除它時,我遇到了災難性故障錯誤。這顯然是因爲我有一個項目源作爲數據綁定。清除ListBox時發生災難性錯誤C#UWP

這解釋了我試圖實現的目標。 enter image description here

這裏是粘貼bin中的所有代碼。

https://pastebin.com/CFs21njZ 

我相信是有關​​方法

public async void loadContacts() 
     { 

      StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Contacts.xml"); 
      XmlReader xmlReader = XmlReader.Create(file.Path); 
      while (xmlReader.Read()) 
      { 
       if (xmlReader.Name.Equals("ID") && (xmlReader.NodeType == XmlNodeType.Element)) 
       { 
        lstd.Add(xmlReader.ReadElementContentAsString()); 
       } 
      } 
      DataContext = this; 
      xmlReader.Dispose(); 
     } 

而且

private async void btnDeleteContact_Click(object sender, RoutedEventArgs e) 
     { 
      StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Contacts.xml"); 
      XDocument xdoc = XDocument.Load(file.Path); 
      if (lstBox.SelectedIndex != -1) 
      { 
       xdoc.Element("Contacts") 
        .Elements("Contact") 
        .Where(x => (string)x.Element("ID") == lstBox.SelectedItem.ToString()).Remove(); 
       //lstBox.SelectedIndex = -1; 
       updateXMLFile(xdoc); 

       //lstBox.Items.Clear(); //Causing catastrophic error    

       loadContacts(); 
      } 
     } 

乾杯的任何幫助。

回答

2

如果將ListBox.ItemSource屬性綁定到'myList',爲什麼不做 myList.Clear();

與項目和ItemSource屬性的交互可以並且會拋出異常