簡體   English   中英

代碼中引用XAML元素時的WPF NullReferenceException

[英]WPF NullReferenceException when XAML element is referenced in 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();
    }

和我的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。 我一直在谷歌搜索大約一個小時,沒有找到任何東西。

myOnlyGrid.Children.Add(MyChart);

InitializeComponent()

myOnlyGrid僅在InitializeComponent調用中創建並初始化,在該行之前它只是null,因此您基本上調用null.Children.Add(MyChart) ,它給出了NullReferenceException

您應該在構造函數的第一行調用InitializeComponent()

此外,這不是放置此類代碼的好地方。 考慮MVVM。

在InitializeComponent()調用之后移動所有代碼。 在此之前執行操作時,尚未創建網格實例。

事實上,如果你去定義那個方法,你會發現你寫的標記只是編寫和執行的代碼的語法糖。 這種情況永遠都是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM