【发布时间】:2018-03-18 08:15:49
【问题描述】:
对于答案,请参见下文。 (https://stackoverflow.com/a/46615550/6826935)
我正在做 WPF 开发并收到此错误。
System.Windows.Markup.XamlParseException 错误 初始化组件();
代码摘录:(MainWindow.xaml.cs)
public MainWindow()
{
InitializeComponent(); // Exception here
this.DataContext = this;
// UI stuff here, deleted
}
异常说明了这一点
为类型集合添加值 'System.Windows.Controls.UIElementCollection' 引发了异常。 行号“23”和行位置“10”。
所以这里是相关文件 (MainWindow.xaml) 中的第 23-24 行
xmlns:local="clr-namespace:Cozyplanes.SudokuApp"
// UI stuff here..., deleted
<local:SudokuUserControl x:Name="SudokuGrid" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="454" Height="451"
Loaded="SudokuGrid_Loaded" KeyUp="SudokuGrid_KeyUp" MouseLeftButtonUp="SudokuGrid_MouseLeftButtonUp"/>
我不知道为什么会这样。 MainWindow 类正在扩展 Window。
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window { ... }
作为参考, SudokuUserControl.xaml.cs
/// <summary>
/// Interaction logic for SudokuUserControl.xaml
/// </summary>
public partial class SudokuUserControl : Window { ... }
在输出中
Step into: Stepping over non-user code 'Cozyplanes.SudokuApp.App.InitializeComponent'
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
这有关系吗?
Module is optimized and the debugger option 'Just My Code' is enabled. -
SudokuUserControl继承自Window。您不能将Window添加为子控件。如果你想真正将它用作控件,它应该从UserControl继承,修复它可能涉及的不仅仅是更改基类。 -
那么我应该从什么修复到什么?
-
您需要将
SudokuUserControl实现为UserControl,而不是Window。它可能就像将public partial class SudokuUserControl : Window更改为public partial class SudokuUserControl : UserControl、将XAML 的根元素修改为UserControl并清理UserControl不支持的属性一样简单。或者这可能会困难得多;如果没有看到SudokuUserControl的更多代码和 XAML,很难说。 -
@BradleyUffner 非常感谢。我完全忘记了
modifying the root element of the XAML to UserControl。它被设置为Window。是的,我有点累了。无论如何,非常感谢你!