1

我有一个相当简单的 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

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

我究竟做错了什么?

4

1 回答 1

5

elementName, atomicNumber,symbol并且atomicWeight似乎没有被初始化。它们的值为 null 并且.ToString()方法将失败。首先尝试将它们初始化为空字符串。

于 2013-01-18T05:06:14.950 回答