0

我正在使用列表框来显示项目列表,下面给出了它的 XAML 代码,

<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>

我只是通过以下 C# 代码填充列表,

foreach (var item in categoryDetails.Category)
        {
           CategoryDisplay data = new CategoryDisplay();
           data.Name = item.accountName;
           data.Id = item.accountID;
           this.List.Items.Add(data);
        }

一切都很顺利,直到最后一步,当

this.List.Items.Add(data);

执行时,会出现一个错误,指出,

An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll but was not handled in user code

可能是什么问题呢?我应该怎么做才能纠正它?

4

2 回答 2

1

听起来您的收藏集this.List.Items尚未初始化。

当您声明您的集合时(让我们假设它是一个 ObservableCollection,但我无法从您的代码中看到该类型应该是什么),那么您需要先将其初始化,new ObservableCollection<AccountDetail>()然后才能向其中添加项目。

于 2013-10-23T12:52:50.243 回答
0

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) };
于 2013-10-23T13:08:09.760 回答