我可以帮您翻译成中文。这段内容涉及到IT技术,是关于创建Windows Phone 8.1应用程序的。我有一个ListBox并且想要在运行时点击按钮时动态添加或插入其他项。但它没有效果或者会崩溃。
在我的页面构造函数中,我有以下代码:
myData = new List<Stuff>() {
new Stuff(){Name="AAA"},
new Stuff(){Name="BBB"},
new Stuff(){Name="CCC"},
new Stuff(){Name="DDD"},
};
myListBox.DataContext = myData;
我的页面的XAML:
<ListBox x:Name="myListBox" ItemsSource="{Binding}" Background="Transparent">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" FontSize="20" Foreground="Red"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
好的,这很有效,当我启动应用程序时,我可以看到列表及其四个项目。
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
myData.Add(new Stuff() { Name = String.Format("Added item #{0}", myData.Count) });
//I tried to set the DataContext again, but it does nothing
myListBox.DataContext = mydata;
//I tried to tell the the list to redraw itself, in winform, the Invalidate() method usually get the job done, so I tried both
myListBox.InvalidateMeasure()
//and / or
myListBox.InvalidateArrange();
//or
myListBox.UpdateLayout();
//I tried
myListBox.Items.Add("Some text");
//or
myListBox.Items.Add(new TextBlock(){Text="Some text"});
//or
(myListBox.ItemsSource as List<Stuff>).Add(new Stuff(){Name="Please work..."});
}
最好的情况就是抛出一个异常:
An exception of type 'System.Exception' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
我之前也用过ListView,但是什么都没改变。附加问题:ListBox和ListView有什么区别?
谷歌并没有提供太多帮助,我找到的东西可能是针对旧版本的Windows Phone或普通的WPF或ASP.Net的...
还有一件奇怪的事情发生了,在将项目添加到列表后,什么也没发生,当我点击旧项目时,会出现灾难性的错误。我还没有在我的列表项上绑定事件。
我快要放弃数据绑定了,只是按照代码逐步构建应用程序。向列表中添加东西不应该那么难,我做错了什么?
ObservableCollection<T>
代替List<T>
。 - Vlad