【问题标题】:WPF NullReferenceException when XAML element is referenced in code在代码中引用 XAML 元素时出现 WPF NullReferenceException
【发布时间】:2013-06-12 21:53:17
【问题描述】:

这是我的代码:

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();
    }

还有我的 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>

由于某种原因,它编译得很好,但在到达 myOnlyGrid.Children.Add() 时会抛出 nullreferenceexception。我已经在谷歌上搜索了大约一个小时,但没有找到任何东西。

【问题讨论】:

    标签: c# wpf xaml visual-studio-2012 nullreferenceexception


    【解决方案1】:

    myOnlyGrid.Children.Add(MyChart);
    

    InitializeComponent()之后

    myOnlyGrid 仅在 InitializeComponent 调用中创建和初始化,并且在该行之前它只是 null 所以你基本上是在调用 null.Children.Add(MyChart) 这给了 NullReferenceException

    【讨论】:

      【解决方案2】:

      您应该在构造函数的第一行调用InitializeComponent()

      此外,这不是放置此类代码的好地方。考虑 MVVM。

      【讨论】:

        【解决方案3】:

        在 InitializeComponent() 调用之后移动所有代码。在此之前执行操作时,尚未创建网格的实例。

        事实上,如果你去定义那个方法,你会发现你编写的标记只是编写和执行代码的语法糖。并且一直如此。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-14
          • 1970-01-01
          相关资源
          最近更新 更多