0

当我按下设备的返回键时出现未处理的异常如何解决这个问题?

我在 windows phone 7 应用程序中实现了收藏夹功能。私人无效FavoriteClick(对象发送者,EventArgs e){

            var favorites = GetFavorites();

            if (favorites.Any(m => m.key == _key))
            {
                RemoveFavorite();
                IsolatedStorageSettings.ApplicationSettings["favorites"] = favorites;
                //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); 
                return;
            }

            AddFavorite();              
    }

    private void AddFavorite()
    {
        const string messageBoxText = "Do you wish to add this page to your favorites?";
        const string caption = "Add Favorite";
        const MessageBoxButton button = MessageBoxButton.OKCancel;
        // Display message box
        var result = MessageBox.Show(messageBoxText, caption, button);

        // Process message box results
        switch (result)
        {
            case MessageBoxResult.OK:
                var favorites = GetFavorites();
                favorites.Add(_page);                   
                IsolatedStorageSettings.ApplicationSettings["favorites"] = favorites;
                break;
        }
    }

    private void RemoveFavorite()
    {
        const string messageBoxText = "Do you wish add remove this page to your favorites?";
        const string caption = "Remove Favorite";
        const MessageBoxButton button = MessageBoxButton.OKCancel;
        // Display message box
        MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button);

        // Process message box results
        switch (result)
        {
            case MessageBoxResult.OK:
                List<MobiRecord> favorites = GetFavorites();

                foreach (MobiRecord m in favorites)
                {
                    if (m.key == _key)
                    {
                        favorites.Remove(m);
                        IsolatedStorageSettings.ApplicationSettings["favorites"] = favorites;                           
                        return;
                    }
                }                    
                break;
        }
    }

问题 :

进入收藏页面后,我添加了一些收藏夹,然后选择任何一个添加的收藏夹,然后单击返回按钮后单击删除收藏夹应用程序自动关闭(我得到了未经处理的异常)。

4

1 回答 1

1

这里的问题很可能是您正在更改您正在执行 foreach 迭代的集合(通过在收藏夹上调用 Remove)。这将导致您的异常(尽管我需要异常详细信息才能确定)。

就像这个从集合中删除的代码片段一样:

favorites.RemoveAll(m => m.key == _key);
于 2012-07-02T18:13:43.740 回答