WPF C# System.NullReferenceException:'Object reference not set to an instance of an object.'

WPF C# System.NullReferenceException: 'Object reference not set to an instance of an object.'

我正在使用 WPF .net 5.0 框架。我正在尝试显示我传递到文本框的值,供用户编辑当前值。

这是代码

    public EditUserDetailsPage1(User user)
    {
        InputFullName.Text = user.Full_Name;
        InputFirstName.Text = user.First_Name;
        InputLastName.Text = user.Last_Name;
        InputEmail.Text = user.Email;
        inputUsername.Text = user.Username;
        InitializeComponent();
    }

这是XAML

<TextBox Style="{StaticResource TextBoxExtend}" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Title="Full Name " VerticalAlignment="Top" hc:InfoElement.Placeholder="Enter full name" Margin="24,75,564,0" Name="InputFullName"/>
<TextBox Style="{StaticResource TextBoxExtend}" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Title="First Name  " VerticalAlignment="Top" hc:InfoElement.Placeholder="Enter First Name" Margin="439,75,296,0" Name="InputFirstName"/>
<TextBox Style="{StaticResource TextBoxExtend}" hc:TitleElement.TitlePlacement="Left" hc:TitleElement.Title="Last Name   " VerticalAlignment="Top" hc:InfoElement.Placeholder="Enter last Name" Margin="709,75,26,0" Name="InputLastName"/>
<TextBox Style="{StaticResource TextBoxExtend}" hc:TitleElement.TitlePlacement="Left" hc:TitleElement.Title="Email" VerticalAlignment="Top" hc:InfoElement.Placeholder="UserEmail@gmail.com" Margin="24,142,564,0" Name="InputEmail"/>
<TextBox Style="{StaticResource TextBoxExtend}" hc:TitleElement.TitlePlacement="Left" hc:TitleElement.Title="Username" VerticalAlignment="Top" hc:InfoElement.Placeholder="Enter username" Margin="439,142,253,0" x:Name="inputUsername"/>

我一直在其他页面使用这种方法,而且效果很好。但是对于这个页面,它给了我这个错误

System.NullReferenceException: 'Object reference not set to an instance of an object.'

我尝试了其他方法,比如先声明它

    User passeduser;
    public EditUserDetailsPage1(User user)
    {

        passeduser = user;

        InputFullName.Text = passeduser.Full_Name;
        InputFirstName.Text = passeduser.First_Name;
        InputLastName.Text = passeduser.Last_Name;
        InputEmail.Text = passeduser.Email;
        inputUsername.Text = passeduser.Username;
        InitializeComponent();
    }

如您所见,正在检索一个值

但它仍然给我一个错误。我遵循了我用于其他页面的相同方法,但它似乎不适用于此页面。非常感谢任何帮助!

这是因为您在 InputFullName 创建之前尝试使用它。

在 WPF 中,UI 元素是在 运行 InitializeComponent 时创建的。

试试这个:

public EditUserDetailsPage1(User user)
{
    InitializeComponent();

    InputFullName.Text = user.Full_Name;
    InputFirstName.Text = user.First_Name;
    InputLastName.Text = user.Last_Name;
    InputEmail.Text = user.Email;
    inputUsername.Text = user.Username;
        
}