DataGrid中的ItemSource错误:调用的目标引发了异常

本文关键字:目标 异常 调用 中的 ItemSource 错误 DataGrid | 更新日期: 2023-09-27 18:30:07


当我调用headersDataGrid.ItemsSource时,应用程序抛出一个异常。有人能帮我调试并确定错误是什么吗?感谢

代码

public static List<Item> getHeaders()
    {
        Item i1 = new Item();
        i1.Label = "TST";
        i1.Description = "This header is only for testing";
        Item i2 = new Item();
        i2.Label = "TS2";
        i2.Description = "This is the second header and is used for testing purposes :)";
        Item i3 = new Item();
        i3.Label = "TS3";
        i3.Description = "This is the THIRD header and is used for testing purposes :D";
        List<Item> headers = new List<Item>();
        headers.Add(i1);
        headers.Add(i2);
        headers.Add(i3);
        return headers;
    }

    public MainWindow()
    {
        displayHeaders();
        InitializeComponent();
    }
    /// <summary>
    /// The purpose of this method is to display all of the headers
    /// </summary>
    public void displayHeaders()
    {
        //List<Item> headers = Database.getHeaders();
        // Testing Purposes
        List<Item> headers = TestingClass.getHeaders();
        // Handle Headers
        headersDataGrid.ItemsSource = headers;          
    }

XML

            <Grid Name="grid_headers" Background="Honeydew">
                <DataGrid x:Name="headersDataGrid" AutoGenerateColumns="True"></DataGrid>
            </Grid>

DataGrid中的ItemSource错误:调用的目标引发了异常

错误指示headersDataGrid为null。尝试在初始化组件调用后移动displayHeaders方法。