Wpf 在xml序列化期间,对象引用未设置为对象的实例,并且在加载时选择combobox项时出现问题
问题1。当我的主标签为空时,我遇到了“对象引用未设置为对象实例”的问题,这是在我尝试单击xml序列化上的保存按钮后发生的。我怎样才能解决这个问题Wpf 在xml序列化期间,对象引用未设置为对象的实例,并且在加载时选择combobox项时出现问题,wpf,xml-serialization,Wpf,Xml Serialization,问题1。当我的主标签为空时,我遇到了“对象引用未设置为对象实例”的问题,这是在我尝试单击xml序列化上的保存按钮后发生的。我怎样才能解决这个问题 private void SaveButton_Click(object sender, RoutedEventArgs e) { string savepath; SaveFileDialog DialogSave = new SaveFileDialog(); // Default file extension Di
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string savepath;
SaveFileDialog DialogSave = new SaveFileDialog();
// Default file extension
DialogSave.DefaultExt = "txt";
// Available file extensions
DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
// Adds a extension if the user does not
DialogSave.AddExtension = true;
// Restores the selected directory, next time
DialogSave.RestoreDirectory = true;
// Dialog title
DialogSave.Title = "Where do you want to save the file?";
// Startup directory
DialogSave.InitialDirectory = @"C:/";
DialogSave.ShowDialog();
savepath = DialogSave.FileName;
DialogSave.Dispose();
DialogSave = null;
FormSaving abc = new FormSaving();
if (!string.IsNullOrEmpty(MajorversionresultLabel.Content.ToString()))
{
abc.Majorversion = MajorversionresultLabel.Content.ToString();
}
abc.Startzbuildfrom = StartzbuildcomboBox.SelectedItem.ToString();
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, abc);
}
}
按照建议,
下面是一行错误:
if (!string.IsNullOrEmpty(MajorversionresultLabel.Content.ToString()))
{
abc.Majorversion = MajorversionresultLabel.Content.ToString();
}
问题2。我使用此行保存我的组合框选择:
abc.Startzbuildfrom = StartzbuildcomboBox.SelectedItem.ToString();
在我的负载中,我有一行:
StartzbuildcomboBox.SelectedItem = abc.Startzbuildfrom
为什么它以前不选择组合框选项?首先,我建议在一个查询中只放一个问题。使它更容易 对于你的第二个问题,我猜你遇到了一个参考变量问题。我认为在SelectedItem上调用ToString()方法实际上创建了一个全新的字符串变量。然后,当您稍后尝试设置所选项目时,它无法找到新字符串作为可能要选择的项目,因为即使这两个字符串具有相同的值,它们也是不同的对象。我可能会建议您: 1) 通过搜索组合框内容来设置所选项目,以查找值与您保存的值匹配的字符串 或
2) 通过说出abc.Startzbuildfrom=StartzbuildcomboBox.SelectedItem保存实际引用。然后从该引用中设置所选项目。我怀疑MajorversionresultLabel为null,或者MajorversionresultLabel.Content为null。因此你的声明
if (!string.IsNullOrEmpty(MajorversionresultLabel.Content.ToString()))
将引发NullReferenceException。请尝试以下方法:
if (MajorversionresultLabel != null && MajorversionresultLabel.Content != null && MajorversionLabel.Content.ToString() != string.Empty)
我打赌您的NullReferenceException将消失。请:不要发布代码墙,一定要发布有关您的问题的特定信息-发生错误的那一行将是一个良好的开始!:-)另外,每个问题请回答一个问题。可能是Hi Aardvark的副本,谢谢您的回复。我这样做了:abc.Startzbuildfrom=StartzbuildcomboBox.SelectedItem;但它声明“不能隐式地将类型‘object’转换为‘string’。”。。知道吗?哦,好的,我之前声明Startzbuildfrom为字符串。。现在它是一个对象,现在一切正常。不过我还是有问题。我会把它贴在新的帖子里