我正在創建一個Windows Phonw 8.1應用程序。我有一個ListBox,當我點擊一個按鈕時,我想在運行時附加/插入其他的。但它不起作用或崩潰。如何在設置DataBinding後將其添加到列表框中?
我在我的頁面的構造我有這樣的:
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有什麼區別?
谷歌是不是真的幫助,我找到的東西可能對於老版本的Windows Phone或正常WPF或ASP.Net的...
而且,這種情況發生一個奇怪的是添加一個項目後列表並沒有任何事情發生,當我點擊一箇舊的項目時,我遇到了災難性的失敗。我的名單上還沒有活動。
我即將放棄數據綁定,只是通過代碼逐個構建我的應用程序。把東西添加到列表中應該不那麼難,我做錯了什麼?
嘗試'的ObservableCollection'而不是'列表'。 –
Vlad
2014-10-08 20:48:44