LongListSelector ItemSource NullReference错误

时间:2014-05-03 03:23:42

标签: c# windows-phone-8 nullreferenceexception

我正在为我的Windows Phone应用程序创建一个长列表选择器

所以我有一个玩家课程

Player.cs

public class Player
{
    public string FirstName
    {
    get;
    set;
    }
    public string LastName;
    public int Age;
    public int Rank;
    public string RankDescreption;
}

这里是 XAML

<phone:LongListSelector Name="playersList" HorizontalAlignment="Left" VerticalAlignment="Top" LayoutMode="List" IsGroupingEnabled="False" Width="446" Margin="24,224,0,-10" Height="639"> <phone:LongListSelector.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding FirstName}" /> </StackPanel> </DataTemplate> </phone:LongListSelector.ItemTemplate> </phone:LongListSelector>

并在页面的构造函数中:

   public SelectProfile()
        {
            ObservableCollection<Player> players = new ObservableCollection<Player>();
            players.Add(new Player { FirstName = "Waseem" });
            players.Add(new Player { FirstName = "Waseem2" });
            players.Add(new Player { FirstName = "Waseem3" });
            players.ItemsSource = players; // assigning data
            InitializeComponent();
        }

我将集合的数据分配给LongListSelector的Item Source 当我调试应用时,它会在players.ItemsSource = players; NullReferenceException

时崩溃

我做错了什么?

2 个答案:

答案 0 :(得分:3)

在InitializeComponent

之后分配ItemsSource
 public SelectProfile()
        {

            InitializeComponent();

            ObservableCollection<Player> players = new ObservableCollection<Player>();
            players.Add(new Player { FirstName = "Waseem" });
            players.Add(new Player { FirstName = "Waseem2" });
            players.Add(new Player { FirstName = "Waseem3" });
            players.ItemsSource = players; // assigning data
        }

答案 1 :(得分:0)

详细解释错误。

您获得空引用错误的原因是您在加载xaml之前分配了长列表选择器的项目源。

在构造函数的运行时,第一步应该初始化component.this方法加载xaml页面中的所有xaml组件。一旦成功加载了xaml(已经执行了initalize componet),你可以在xaml.cs页面中引用控件。