WPF NullReferenceException when XAML element is referenced in code

混江龙づ霸主 提交于 2020-01-05 02:58:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!