我创建并初始化了一个相当大的字典,并在启动应用程序时遇到此错误:
An unhandled exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: Zeilennummer "3" und Zeilenposition "9" von "Durch den Aufruf des
Konstruktors für Typ "AbiZeitung.MainWindow", der den angegebenen Bindungseinschränkungen
entspricht, wurde eine Ausnahme ausgelöst.".
If there is a handler for this exception, the program may be safely continued.
这是字典的一部分:
Dictionary<string, string> teacherList = new Dictionary<string, string>()
{
{"Mr", "M"},
{"Mr", "D"},
{"Mr", "S"},
{"Mr", "W"}
};
猜猜为什么会这样?
请您参考如下方法:
A Dictionary<T,U>需要有唯一键。现在,您的集合初始化程序在尝试添加 ArgumentException 时会引发异常( {"Mr","D"} ) ,因为“Mr”已经是一个键。
有关详细信息,请参阅 Dictionary.Add ,在异常(exception)情况下:
ArgumentException: An element with the same key already exists in the Dictionary.
如果您的 View 创建了这个字典,即使是间接创建的(即:它在从 xaml 生成的 ViewModel 中),您将得到一个异常,这反过来会导致 XamlParseException发生。
如果您需要这样的收藏,我建议制作一个 ObservableCollection<T> (或 List<T>,如果这不会改变)包含两个字符串的自定义类型。
