解析外部XAML文件时出现了一个非常奇怪的问题。预先的历史是我想加载一个外部XAML文件,其中包含要处理的内容。但是我想加载尽可能多的不同文件。这是通过卸载旧的和加载新的。XamlReader.Load()的奇怪行为?
我的问题是: 当我第一次加载xaml时,一切都很好,一切都应该如此。 但是,当我第二次加载相同的xaml时,im Loading的对象的每个条目都有两次。如果我再运行一次,每个对象都有三次,依此类推...
要自己调试项目,请下载它here。该函数从文件“Control Panel.xaml.cs”的第137行开始。我真的不知道这是什么。这是我的错还是仅仅是一个错误?如果是,是否有解决方法?
/// <summary>
/// Load a xaml file and parse it
/// </summary>
public void LoadPresentation()
{
this.Title = "Control Panel - " + System.IO.Path.GetFileName(global.file);
System.IO.FileStream XAML_file = new System.IO.FileStream(global.file, System.IO.FileMode.Open);
try
{
System.IO.StreamReader reader = new System.IO.StreamReader(XAML_file);
string dump = reader.ReadToEnd(); //This is only for debugging purposes because of the strange issue...
XAML_file.Seek(0, System.IO.SeekOrigin.Begin);
presentation = (ResourceDictionary)XamlReader.Load(XAML_file);
//Keys the resourceDictionary must have to be valid
if (presentation["INDEX"] == null || presentation["MAIN_GRID"] == null || presentation["CONTAINER"] == null || presentation["LAYOUTLIST"] == null)
{
throw new Exception();
}
//When this list is loaded, every item in it is there twice or three times or four... Why????
TopicList Index = null;
Index = (TopicList)presentation["INDEX"];
for (int i = 0; i < topics.Count;)
{
topics.RemoveAt(i);
}
foreach (TopicListItem item in Index.Topics)
{
topics.Insert(item.TopicIndex, (Topic)presentation[item.ResourceKey]);
}
lv_topics.SelectedIndex = 0;
selectedIndex = 0;
}
catch
{
System.Windows.Forms.MessageBox.Show("Failed to load XAML file \"" + global.file + "\"", "Parsing Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
presentation = null;
}
finally
{
XAML_file.Close();
}
}
编辑:
我试图序列化从XamlReader和输出读取无处任何元素childElement对象......但是,如果我拉出来的对象字典,孩子们都在那里(重复和三重,但在那里)。
我已经尝试过
topics.Clear();
和
topics=new ObservableCollection<TopicListItem>();
lv_topics.ItemsSource=topics;
是的,解决了它,谢谢。但为什么?我不明白为什么这些对象连接在一起... – CShark 2012-02-26 12:09:26
要回答你,我不知道为什么。我用你的代码玩了大约一个小时,以确定我做了什么。我将XamlReader.Load取消了,它引入了正确数量的主题,我注意到当您将演示文稿投射到TopicList时,会出现额外的主题。我猜测它与你的TopicList类型中的静态声明有关。你将它设置为null然后重新分配它,我相信它会将旧数据连接起来。 – 2012-02-26 19:14:24
但是不是一个静态的DependencyProperty处理绑定的常用方法?如果是这样,那么应该有首先显示的话题不应该吗?我向其他几个人展示了这个错误,他们的最终观点是,.NET Framework中存在一个错误。我会尝试重现这一点并收集更多信息...... – CShark 2012-02-27 16:22:18