【问题标题】:Isolated Storage in C# / WPC#/WP 中的隔离存储
【发布时间】:2014-04-27 23:11:59
【问题描述】:

我目前正在尝试将隔离存储添加到 Windows Phone / C# 上的简单宠物店应用程序。 (请注意,这是我第一次尝试隔离存储,所以我可能会离开

我只想将隔离存储添加到我的“购物篮”中,这样​​当您将商品添加到购物篮然后关闭应用程序时,当您重新启动应用程序时,该商品仍会在我的购物篮中。

首先,这里是我在篮子中添加“动物物品”的代码。

private void list_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
    {

        Shop selectedPet = list.SelectedItem as Shop;
        //thisApp.tempItem = selectedPet;

        String photo = selectedPet.Photo;
        String breed = selectedPet.Breed;
        String name = selectedPet.Name;
        DateTime age = selectedPet.Age;
        double price = selectedPet.Price;

        NavigationService.Navigate(new Uri("/Profile.xaml?&breed=" + breed + "&age=" + age + "&price=" + "€" + price + "&name=" + name + "&" + "photo=" + photo, UriKind.Relative));
    }

这段代码将所选项目的个别信息传递到“个人资料页面”

  protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        try
        {
            //String temp1 = thisApp.tempItem.Name;
            string photo;
            string name;
            string age;
            string breed;
            string price;

            if (NavigationContext.QueryString.TryGetValue("photo", out photo))
            {
                imgPhotoHolder.Source = null;

                BitmapImage myimage = new BitmapImage
                (new Uri("/Assignment 1;component/Images/" + photo, UriKind.RelativeOrAbsolute));

                imgPhotoHolder.Source = myimage;
            }
            if (NavigationContext.QueryString.TryGetValue("name", out name))
            {
                nameTxtBlock.Text = name;
            }
            if (NavigationContext.QueryString.TryGetValue("age", out age))
            {
                ageTxtBlock.Text = age;
            }
            if (NavigationContext.QueryString.TryGetValue("breed", out breed))
            {
                breedTxtBlock.Text = breed;
            }
            if (NavigationContext.QueryString.TryGetValue("price", out price))
            {
                priceTxtBlock.Text = price;
            }
            Find(photo);
        }
        catch
        {
            MessageBox.Show("Image did not load...");
        }
    }

然后,这会将信息片段添加到个人资料页面,但出现了问题,我没有传递对象,而是传递了单独的信息,因此基本上分解了对象,所以为了纠正这个问题,我使用了下面的代码并且能够在按钮按下事件时将其传递到我的购物篮中。

 private void Find(String str)
    {
        foreach (Shop pet in thisApp.myshop)
        {
            if (pet.Photo == str)
            {
                index = thisApp.myshop.IndexOf(pet);
            }
        }
    }

 private void btnAddToBasket_Click(object sender, RoutedEventArgs e)
    {
        bool found = false;
        try
        {

            foreach (Shop pet in thisApp.basket)
            {
                if(thisApp.myshop[index].Photo == pet.Photo)
                {
                    found = true;
                }
            }
            if (found)
            {
                MessageBox.Show("Item already in Basket");
            }
            else
            {
                thisApp.basket.Add(thisApp.myshop.ElementAt(index));
            }
         }
        catch
        {
            MessageBox.Show("That didn't work...");
        }
    } 

现在问题出现了,我已将隔离存储代码放入 App.xaml 中,如此处所示。

 public void WriteBasketToStorage()
    {
        using (IsolatedStorageFile cart = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("Cart.xml",
                                                                FileMode.Create, cart))
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                {
                    writer.WriteStartElement("Pets");
                    foreach (Shop currPet in basket)
                    {
                        writer.WriteStartElement("Pet");
                        writer.WriteElementString("Name", currPet.Name);
                        writer.WriteElementString("Age", currPet.Age.ToString());
                        writer.WriteElementString("Breed", currPet.Breed);
                        //writer.WriteElementString("Type", currPet.Type);
                        //writer.WriteElementString("Stock", currPet.Stock.ToString());
                        writer.WriteElementString("Price", currPet.Price.ToString());
                        writer.WriteElementString("Photo", currPet.Photo);
                        writer.WriteEndElement();

                    }
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                    writer.Flush();
                }
            }
        }
    }
    public void RetrieveBasketData()
    {
        try
        {
            using (IsolatedStorageFile cart = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream isoStream = cart.OpenFile("Basket.xml", FileMode.Open))
            {

                try
                {

                    XmlReader reader = XmlReader.Create(isoStream);
                    reader.ReadToDescendant("Pet");
                    basket.Clear();

                    while (reader.Read())
                    {

                        //reader.MoveToFirstAttribute();

                        reader.ReadToFollowing("Name");
                        string name = reader.ReadElementContentAsString();

                        reader.ReadToFollowing("Age");
                        string age = reader.ReadElementContentAsString();

                        reader.ReadToFollowing("Breed");
                        string breed = reader.ReadElementContentAsString();

                        //reader.ReadToFollowing("Type");
                        //string type = reader.ReadElementContentAsString();

                        //reader.ReadToFollowing("Stock");
                        //string stock = reader.ReadElementContentAsString();

                        reader.ReadToFollowing("Price");
                        string price = reader.ReadElementContentAsString();

                        reader.ReadToFollowing("Photo");
                        string photo = reader.ReadElementContentAsString();

                        DateTime date = DateTime.Parse(age);
                        decimal price1 = Decimal.Parse(price);

                        //basket.Add(new Shop(name, age, breed, type, stock, date, price1, photo ));
                        basket.Add(new Shop(photo, breed, name, date, price1));
                    }
                }
                catch
                {

                }


            }

        }

        catch (IsolatedStorageException ise)
        {
            MessageBox.Show(ise.Message);
        }
    }

我已尝试使用此代码在我的购物篮页面中检索它

 public void ReadBasketDetailsFromStorage()
    {
        try
        {
            using (IsolatedStorageFile petStore = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream isoStream = petStore.OpenFile("Basket.xml", FileMode.Open))
            {

                try
                {

                    XmlReader reader = XmlReader.Create(isoStream);
                    reader.ReadToDescendant("Pet");

                    while (reader.Read())
                    {

                        //reader.MoveToFirstAttribute();

                        reader.ReadToFollowing("Name");
                        string name = reader.ReadElementContentAsString();

                        reader.ReadToFollowing("Age");
                        string age = reader.ReadElementContentAsString();

                        reader.ReadToFollowing("Breed");
                        string breed = reader.ReadElementContentAsString();

                        //reader.ReadToFollowing("Type");
                        //string type = reader.ReadElementContentAsString();

                        //reader.ReadToFollowing("Stock");
                        //string stock = reader.ReadElementContentAsString();

                        reader.ReadToFollowing("Price");
                        string price = reader.ReadElementContentAsString();

                        reader.ReadToFollowing("Photo");
                        string photo = reader.ReadElementContentAsString();

                        DateTime date = DateTime.Parse(age);
                        decimal price1 = Decimal.Parse(price);

                        //basket.Add(new Shop(name, age, breed, type, stock, date, price1, photo ));
                        thisApp.basket.Add(new Shop(photo, breed, name, date, price1));


                    }
                }
                catch
                {

                }


            }

        }

        catch (IsolatedStorageException ise)
        {
            MessageBox.Show(ise.Message);
        }
    }

我遇到的错误是它不包含需要 5 个参数的构造函数。我试图通过使用不需要的字段(如“类型”和“库存”)来修复它,但它随后说它不包含需要 7 个参数等的构造函数。

目前我不确定如何处理此问题,非常感谢您提供有关此问题的建议/帮助。如果您需要更多代码来完全理解我的问题,请索取,我会将其添加到帖子中。

提前致谢, 杰森

【问题讨论】:

标签: c# windows-phone-8 isolatedstorage


【解决方案1】:

您可以在代码中改进以下几点:

//first of all lets make classes for your Shop and Basket:
public class Basket
{
    public List<Shop> Items = new List<Shop>();
}

public class Shop
{
    public String photo { get; set; }
    public String breed { get; set; }
    public String name { get; set; }
    public String age_value  // for serialization
    {
        get { return age.ToString("D"); }
        set { age = DateTime.Parse(value); }
    }
    public double price { get; set; }

    [XmlIgnore]
    public DateTime age { get; set; }
}

如您所见,我为序列化添加了一个额外的文件。序列化您的购物篮比手动读取/写入所有元素更容易。您可以read about Serialization here,并且可能在许多教程中。有了这个,你的保存和加载看起来会更简单:

// somewhere in your code (for example MainPage class)
Basket basket = new Basket();
// and upon click, there were some items added:
basket.Items.Add(new Shop { photo = "aaa.png", breed = "bbb", age = new DateTime(2000, 11, 20, 20, 12, 10), name = "turtle", price = 100 });

public void SaveBasket()
{
    using (IsolatedStorageFile cart = IsolatedStorageFile.GetUserStoreForApplication())
    using (IsolatedStorageFileStream isoStream = cart.CreateFile("Cart.xml"))
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(Basket));
        xmlSerializer.Serialize(isoStream, basket);
    }
}

public void LoadBasket()
{
    using (IsolatedStorageFile cart = IsolatedStorageFile.GetUserStoreForApplication())
    using (IsolatedStorageFileStream isoStream = cart.OpenFile("Cart.xml", FileMode.Open))
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(Basket));
        basket = (Basket)xmlSerializer.Deserialize(isoStream);
    }
}

至于在页面之间传递数据 - 这是一个很长的故事,如果您搜索“页面之间传递数据”,那么您肯定会发现很多命中。最简单的方法是将您的basket 设为静态,然后从其他页面访问它,如下所示:MainPage.basket。如果您想传递数据,我建议您像这样使用PhoneApplicationService.State Property

 // when Navigating:
 if (PhoneApplicationService.Current.State.ContainsKey("data")) PhoneApplicationService.Current.State["data"] = basket;
 lse PhoneApplicationService.Current.State.Add("data", basket);

 // in constructor of next page, or OnNavigatedTo event:
 Basket passedOne = PhoneApplicationService.Current.State["data"] as Basket;

这些只是简单的示例,您可以通过多种方式实现目标。希望这个答案能给你带来一些新的可能性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多