WPF抛出的ShowDialog与当前状态不一致
本文关键字:状态 不一致 ShowDialog WPF | 更新日期: 2023-09-27 18:12:15
当我在WPF中打开SaveFileDialog
时,我一直得到以下错误,但我必须诚实地说,错误对我来说没有多大意义。
开发人员信息:
由于控件"System.Windows.Controls.ListBox Items"的生成器抛出此异常。Count:4' with name '(未命名)'已接收到一系列CollectionChanged事件,这些事件与Items集合的当前状态不一致。检测到以下差异:累计计数2与实际计数4不同。[累计计数为(上次重置计数+自上次重置以来的#添加- #删除)]
以下一个或多个来源可能引发了错误的事件:System.Windows.Controls.ItemContainerGeneratorSystem.Windows.Controls.ItemCollectionSystem.Windows.Data.ListCollectionView* XmlDiff.Gui.ViewModels.MTObservableCollection ' 1[[系统。String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](星号来源被认为更有可能是问题的原因。)
最常见的原因是(a)更改集合或其Count而没有引发相应的事件,以及(b)引发带有错误索引或项参数的事件。
异常的堆栈跟踪描述了不一致是如何被检测到的,而不是它们是如何发生的。要获得更及时的异常,请设置附加的属性"PresentationTraceSources"。将生成器上的TraceLevel'设置为值'High',然后重新运行场景。一种方法是运行类似于下面的命令:System.Diagnostics.PresentationTraceSources.SetTraceLevel (myItemsControl。ItemContainerGenerator System.Diagnostics.PresentationTraceLevel.High)从"立即"窗口中。这将导致检测逻辑在每次CollectionChanged事件之后运行,因此它将减慢应用程序的速度。
执行以下方法时出现错误。它不会在GUI线程上运行,但是当我创建一个新的SaveFileDialog时,这应该很重要。
private string ShowSaveFileDialog(string defaultName)
{
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog
{
FileName = defaultName,
DefaultExt = ".xml",
Filter = "Xml documents (.xml)|*.xml"
};
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
return dlg.FileName;
return null;
}
必须有一些代码将文件添加到另一个线程上的文件夹中。在访问集合之前,应该考虑锁定集合。
http://msdn.microsoft.com/en-gb/library/c5kehkcz.aspxlock (mycollection){
//modify the collection in a threadsafe manner
}