将按钮注入现有网格 //Xaml //代码隐藏 Button hello=新建按钮(); hello.Content=“hello World”; _Grid.Children.Add(hello);
试图将hello按钮插入_网格,但显示以下错误: System.NullReferenceException:“对象引用未设置为对象的实例。”将按钮注入现有网格 //Xaml //代码隐藏 Button hello=新建按钮(); hello.Content=“hello World”; _Grid.Children.Add(hello);,xaml,uwp,Xaml,Uwp,试图将hello按钮插入_网格,但显示以下错误: System.NullReferenceException:“对象引用未设置为对象的实例。” _网格为空。在调用InitializeComponent()方法之前,我可以在执行这些代码时重现您的问题。InitializeComponent()方法由XAML设计器自动创建和管理,它定义了您在窗口上看到的所有内容。使用设计器在窗口上完成的所有操作都会生成代码。添加的每个控件和属性集都将生成代码,这些代码将进入InitializeComponent()
_网格为空。在调用InitializeComponent()方法之前,我可以在执行这些代码时重现您的问题。InitializeComponent()方法由XAML设计器自动创建和管理,它定义了您在窗口上看到的所有内容。使用设计器在窗口上完成的所有操作都会生成代码。添加的每个控件和属性集都将生成代码,这些代码将进入InitializeComponent()方法 因此,如果在InitializeComponent()方法之前插入此按钮,则网格不会生成,它为null。因此,当您使用此网格时,它会报告
NullReferenceException
。请在调用InitializeComponent()
方法后按如下方式操作这些代码
// Xaml
<Grid x:Name="_Grid" Width="926" Margin="603,140,391,55">
</Grid>
// Code behind
Button hello = new Button();
hello.Content = "Hello World";
_Grid.Children.Add(hello);
是的,成功了,非常感谢你!
public MainPage()
{
this.InitializeComponent();
Button helloBtn = new Button();
helloBtn.Content = "Hello World";
_Grid.Children.Add(helloBtn);
}