在代码中引用 XAML 元素时的 WPF NullReferenceException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17076003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF NullReferenceException when XAML element is referenced in code
提问by sirdank
Here's my code:
这是我的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
//myOnlyGrid = new Grid();
Chart MyChart = new Chart();
ColumnSeries b = new ColumnSeries();
b.Title = "B";
b.IndependentValueBinding = new System.Windows.Data.Binding("Key");
b.DependentValueBinding = new System.Windows.Data.Binding("Value");
b.ItemsSource = new List<KeyValuePair<string, int>> {
new KeyValuePair<string, int>("1", 100),
new KeyValuePair<string, int>("2", 75),
new KeyValuePair<string, int>("3", 150)
};
MyChart.Series.Add(b);
Grid.SetColumn(MyChart, 0);
Thread.Sleep(1000);
myOnlyGrid.Children.Add(MyChart);
InitializeComponent();
}
and my XAML:
和我的 XAML:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Name="myOnlyGrid">
</Grid>
For some reason, it compiles fine but throws a nullreferenceexception whenever it reaches myOnlyGrid.Children.Add(). I've been googling for about an hour and haven't found anything.
出于某种原因,它编译得很好,但是每当它到达 myOnlyGrid.Children.Add() 时就会抛出一个 nullreferenceexception。我已经在谷歌上搜索了大约一个小时,但没有找到任何东西。
回答by Blablablaster
Put
放
myOnlyGrid.Children.Add(MyChart);
after InitializeComponent()
后 InitializeComponent()
myOnlyGridgets created and initialized only in InitializeComponentcall and before that line it's simply null so you are basically calling null.Children.Add(MyChart)which gives NullReferenceException
myOnlyGrid仅在InitializeComponent调用中创建和初始化,在该行之前它只是 null 所以你基本上是在调用null.Children.Add(MyChart)它给出NullReferenceException
回答by Michael Gunter
You should call InitializeComponent()on the first line of your constructor.
您应该调用InitializeComponent()构造函数的第一行。
Also, this isn't a great place to put this type of code. Consider MVVM.
此外,这不是放置此类代码的好地方。考虑 MVVM。
回答by Mike Perrenoud
Move all the code after the InitializeComponent() call. When performing the operation before that the instance of the grid hasn't yet been created.
在 InitializeComponent() 调用之后移动所有代码。在此之前执行操作时,尚未创建网格实例。
In fact, if you go to definition on that method you'll see that the markup you write is just syntactic sugar for code that is written and executed. And that's been the case forever.
事实上,如果您查看该方法的定义,您会发现您编写的标记只是编写和执行的代码的语法糖。情况一直如此。

