Reputation: 806
I'm using listbox to display a list of items,the XAML code for it is given below,
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="List" HorizontalAlignment="Left" Height="612" Margin="6,7,0,0" VerticalAlignment="Top" Width="443" SelectionChanged="List_SelectionChanged_1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="400" Height="50">
<TextBlock x:Name="tbName" Width="400" Height="44" FontSize="22" FontWeight="Bold" Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
And i just populate the list by the following C# code,
foreach (var item in categoryDetails.Category)
{
CategoryDisplay data = new CategoryDisplay();
data.Name = item.accountName;
data.Id = item.accountID;
this.List.Items.Add(data);
}
Everything goes fine until the last step,when
this.List.Items.Add(data);
is executed, there comes an error stating that,
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll but was not handled in user code
What could be the problem? What should i do to rectify it??
Upvotes: 0
Views: 147
Reputation: 2111
A System.Windows.Controls.ItemCollection.ItemCollection (your Items) should be initialised to an empty collection by default according to the documentation. Have you set it to null somewhere in your code execution block? The property does not have a setter in wp7.
Either way, a better and more efficient approach to assigning a data source to a control is to create your collection in one go and then assign it to the controls ItemSource property
var data = new[] { 1, 2, 3, 4 };
this.List.ItemsSource = from i in data select new CategoryDisplay() { id = i, Name = i.ToString(CultureInfo.InvariantCulture) };
Upvotes: 0
Reputation: 29953
It sounds like your collection at this.List.Items
has not been initialised.
When you declare your collection (let's assume for a minute that it is an ObservableCollection, but I can't see from your code what the type should be) then you need to initialise it to new ObservableCollection<AccountDetail>()
before you can add items to it.
Upvotes: 1