问题
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:
<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.
回答1:
Put
myOnlyGrid.Children.Add(MyChart);
after InitializeComponent()
myOnlyGrid
gets created and initialized only in InitializeComponent
call and before that line it's simply null so you are basically calling null.Children.Add(MyChart)
which gives NullReferenceException
回答2:
You should call InitializeComponent()
on the first line of your constructor.
Also, this isn't a great place to put this type of code. Consider MVVM.
回答3:
Move all the code after the InitializeComponent() call. When performing the operation before that the instance of the grid hasn't yet been created.
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.
来源:https://stackoverflow.com/questions/17076003/wpf-nullreferenceexception-when-xaml-element-is-referenced-in-code