Question

I am creating a Long list Selector for my Windows Phone app

So I have a class for Players

Player.cs

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

and here the 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>

and in the Constructor of the page :

   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();
        }

I assigned the Data of the collection to the Item Source of the LongListSelector When I debug the app , it crashes at players.ItemsSource = players; with NullReferenceException

What did I do wrong ?

Was it helpful?

Solution

Assign the ItemsSource after InitializeComponent

 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
        }

OTHER TIPS

Explaining a bit more on the Error.

the reason you are getting null reference error is you are assigning the item source of long list selector before the xaml has been loaded.

at the run time in your constructor the first step should be initialize component.this method loads all the xaml components in your xaml page. once the xaml has been loaded successfully(initalize componet has been executed) you can to refer the controls in the xaml.cs page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top