我希望這個問題不是愚蠢的,我試圖尋找一個解決方案5小時,並且大多數在這個網站上找到有用的東西,但我無法解決我的問題。添加和更新數據綁定列表框C#windows phone
我有我的物品類別中只有這個屬性:
public string ItemName { get; set; }
和A類持有項目:
public class ShoppingListItems
{
public static List<Item> ItemCollection { get; set; }
public ShoppingListItems()
{
ItemCollection = new List<Item>();
AddAnItem("test");
}
public static void AddAnItem(string name)
{
ItemCollection.Add(new Item()
{
ItemName = name
});
}
}
而在我的XAML文件,結合相關的代碼是:
xmlns:application="clr-namespace:ShoppingListTest"
<Grid.Resources>
<application:ShoppingListItems x:Key="ShoppingListItems" />
</Grid.Resources>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" DataContext="{StaticResource ShoppingListItems}">
<ListBox x:Name="listBox1" Height="Auto" ItemsSource="{Binding ItemCollection, Mode=TwoWay}">
<TextBlock x:Name="textBlock1" Text="{Binding ItemName}" FontSize="50" />
然後在我的MainPage.xaml.cs中,在KeyDown的方法中我有:
ShoppingListItems.AddAnItem(textBox1.Text);
該列表很好,並顯示列表框中的「測試」,但添加到列表不起作用,我試圖看看一些NotifyPropertyChanged的東西,沒有任何運氣。
任何想法,我需要做什麼來更新列表框?如果任何人有一些技巧會使這項工作,我會很高興!
如果你真的想要一個單一的全球列表中使用Singleton模式。向ShoppingListItems中添加一個靜態get屬性,如ShoppingListItems.Instance,它返回一個ShoppingListItems對象。然後在ShoppingListItems中使構造函數爲private,並創建一個私有靜態_instance = new ShoppingListItems()。然後讓ShoppingListItems.Instance返回_instance。 – Zik 2012-02-18 00:41:50