xaml用户控件对象引用未设置为对象的实例

时间:2013-01-18 04:51:22

标签: xaml windows-8

我有一个相当简单的Windows 8 XAML / C#UserControl:

  <UserControl
    x:Class="periodicTable.cell"
    x:Name="periodicTableCell"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:periodicTable"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="100"
    d:DesignWidth="65">

<Grid Background="White">
    <Grid.RowDefinitions>
        <RowDefinition Height="15"/>
        <RowDefinition Height="20"/>
        <RowDefinition Height="50"/>
        <RowDefinition Height="15"/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0" x:Name="txtElementName"/>
    <TextBlock Grid.Row="1" x:Name="txtAtomicNumber"/>
    <TextBlock Grid.Row="2" x:Name="txtSymbol"/>
    <TextBlock Grid.Row="3" x:Name="txtAtomicWeight"/>
</Grid>

我的代码背后是:

namespace periodicTable
{
    public sealed partial class cell : UserControl
    {

        public string elementName { get; set; }
        public string atomicNumber { get; set; }
        public string symbol { get; set; }
        public string atomicWeight { get; set; }

        public cell()
        {
            this.InitializeComponent();

            this.txtElementName.Text = elementName.ToString();
            this.txtAtomicNumber.Text = atomicNumber.ToString();
            this.txtAtomicWeight.Text = atomicWeight.ToString();
            this.txtSymbol.Text = symbol.ToString();
        }
    }
}

当我将此控件添加到我的MainPage XAML时:

xmlns:local="using:periodicTable"

然后当我尝试将其添加到我的网格时:

<local:cell Grid.Row="0" Grid.Column="2"/>

我收到错误消息:object reference not set to an instance of an object

我应该注意到我计划在许多行和列中重用这个用户控件......

我做错了什么?

1 个答案:

答案 0 :(得分:5)

elementNameatomicNumbersymbolatomicWeight似乎未初始化。它们的值将为null,.ToString()方法将失败。首先尝试将它们初始化为空字符串。