You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向新窗口传字符串时触发Object reference not set to instance of an object错误

问题分析与解决

错误原因

WPF中,InitializeComponent()方法负责解析XAML文件并实例化所有命名的UI控件。你当前的代码先尝试给lblCountryName.Content赋值,但此时lblCountryName还未被创建(InitializeComponent()还未执行),因此触发了空引用异常。

修正代码

将InitializeComponent()移到构造方法最开头,确保UI控件先完成实例化,再进行赋值操作:

public partial class CountryView : Window
{
    public CountryView(string thisCountry)
    {
        InitializeComponent(); // 先初始化所有UI控件
        lblCountryName.Content = thisCountry; // 再给Label赋值
    }
}

额外建议

可以对传入的字符串做空值判断,避免后续潜在的空值问题:

public partial class CountryView : Window
{
    public CountryView(string thisCountry)
    {
        InitializeComponent();
        lblCountryName.Content = string.IsNullOrEmpty(thisCountry) ? "未知国家" : thisCountry;
    }
}

内容的提问来源于stack exchange,提问作者Orlak333

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:22:30