我正在深入研究Windows Phone开发,并开始接受WP上Silverlight的一些功能,但我正在努力使用XML:
我正在尝试将一些对象序列化为XML,然后读取所述XML并将其序列化为对象。然后,我将使用ObservableCollection
作为列表框的ItemsSource
来填充列表框。
我已经确保数据绑定工作正常;如果我只生成对象并将它们放入Observable Collection
然后将其作为ItemsSource
放置,则没有问题。似乎我的代码的XML部分是错误的。所有内容都编译并执行得足够好,但列表框仍为空:(
此代码在应用程序启动时执行(效果不是很好但适用于我的测试):
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
ObservableCollection<Quote> quotes = new ObservableCollection<Quote>();
for (int i = 0; i < 10; i++)
{
Quote quote = new Quote()
{
Author = "Author #" + i.ToString(),
QuoteText = "This is quote #" + i.ToString(),
};
quotes.Add(quote);
}
XmlWriterSettings xmlwrtrstngs = new XmlWriterSettings();
xmlwrtrstngs.Indent = true;
using(IsolatedStorageFile isostrg = IsolatedStorageFile.GetUserStoreForApplication())
{
using(IsolatedStorageFileStream isoflstrm = isostrg.OpenFile("Quotes.xml", FileMode.Create))
{
XmlSerializer xmlsrlzr = new XmlSerializer(typeof(QuoteCollection));
using(XmlWriter xmlwrtr = XmlWriter.Create(isoflstrm, xmlwrtrstngs))
{
xmlsrlzr.Serialize(xmlwrtr, quoteCollection);
}
}
}
loadData();
}
void loadData()
{
try
{
using(IsolatedStorageFile isostrg = IsolatedStorageFile.GetUserStoreForApplication())
{
using(IsolatedStorageFileStream isoflstrm = isostrg.OpenFile("Quotes.xml", FileMode.Open))
{
XmlSerializer xmlsrlzr = new XmlSerializer(typeof(QuoteCollection));
QuoteCollection quoteCollectionFromXML = (QuoteCollection)xmlsrlzr.Deserialize(isoflstrm);
LstBx.ItemsSource = quoteCollectionFromXML.Quotes;
}
}
}
catch(Exception)
{
Console.Write("Something went wrong with the XML!");
}
}
QuoteCollection
public class QuoteCollection : INotifyPropertyChanged
{
ObservableCollection<Quote> quotes;
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Quote> Quotes
{
get { return quotes; }
set
{
if(quotes != value)
{
quotes = value;
raisePropertyChanged("Quotes");
}
}
}
protected virtual void raisePropertyChanged(string argPropertyChanged)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(argPropertyChanged));
}
}
}
引用
public class Quote : INotifyPropertyChanged
{
string author;
string quoteText;
public event PropertyChangedEventHandler PropertyChanged;
public string Author
{
get
{
return author;
}
set
{
if(author != value)
{
author = value;
onPropertyChanged("Author");
}
}
}
public string QuoteText
{
get
{
return quoteText;
}
set
{
if(quoteText != value)
{
quoteText = value;
onPropertyChanged("QuoteText");
}
}
}
protected virtual void onPropertyChanged(string argProperty)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(argProperty));
}
}
}
任何见解都会非常感激:)
答案 0 :(得分:2)
您使用QuoteCollection
作为类型进行序列化,但实际上是在写出ObservableCollection<Quote>
。
答案 1 :(得分:0)
忘记将ObservableCollection放入我之前创建的QuoteCollection实例中(未在发布的代码中显示)。