2014-10-08 53 views
3

我正在創建一個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的...

而且,這種情況發生一個奇怪的是添加一個項目後列表並沒有任何事情發生,當我點擊一箇舊的項目時,我遇到了災難性的失敗。我的名單上還沒有活動。

我即將放棄數據綁定,只是通過代碼逐個構建我的應用程序。把東西添加到列表中應該不那麼難,我做錯了什麼?

+3

嘗試'的ObservableCollection '而不是'列表'。 – Vlad 2014-10-08 20:48:44

回答

0

需要實現與INotifyPropertyChanged接口自己的東西要麼做,或者你使用具有它內置的一類。

MSDN INotifyPropertyChanged Interface

嘗試

using System.ComponentModel; 
using System.Collections.ObjectModel; 

public class Stuff 
{ 
    public Stuff(string name) 
    { 
     this.Name = name; 
    } 

    public string Name { get; set; } 
} 


ObservableCollection<Stuff> myData = new ObservableCollection<Stuff>(); 


myData.Add(new Stuff("abcd")); 
+0

非常感謝! – 2014-10-09 05:33:13

+0

我會更改我的代碼以使用ObservableCollection ,我會記住INotifyPropertyChanged是因爲我在處理應用程序中實際使用的部分時: 假設我沒有控制源代碼(在dll),即:一個具有列表的東西。我如何告訴我的應用程序FrameworkElement的DataContext已更改? – 2014-10-09 05:43:14

+0

@GuillaumeGrillonLabelle如果你沒有源代碼或者他們沒有實現回調函數/委託,這將是非常困難的。最好,我可以給你的是刷新列表(緩衝區)並添加/刪除任何差異並更新ObserableCollection。您可能想了解一下MVVM模式,我有一個非常基本的例子在這裏閱讀:http://stackoverflow.com/questions/25613212/how-to-implement-a-navigation-button-in-shared-application -resources/25627927#25627927 – 2014-10-09 06:31:39

相關問題