【发布时间】:2014-10-08 20:45:57
【问题描述】:
我正在创建一个 Windows Phonw 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>
好的,这很好,当我启动应用程序时,我可以看到包含 4 个项目的列表。
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 有什么区别?
Google 并没有真正提供帮助,我发现的东西可能适用于旧版本的 Windows Phone 或普通 WPF 或 ASP.Net...
另外,发生的一件奇怪的事情是在将一个项目添加到列表后没有任何反应,当我点击一个旧项目时,我遇到了灾难性的失败。我的列表项上还没有活动。
我即将放弃数据绑定,而只是逐段代码构建我的应用程序。将东西添加到列表中应该不难,我做错了什么?
【问题讨论】:
-
试试
ObservableCollection<T>而不是List<T>。
标签: c# xaml windows-phone-8.1