我有一个经典的ListBox控件绑定到我的Silverlight应用程序中的List for WP8。我在列表中添加了一些新项目后需要更新它。怎么做?
请不要建议使用ObservableCollection - 我需要解决List的问题。
答案 0 :(得分:1)
如果你没有使用MVVM设计模式而不是将ListBox ItemSource设置为null并再次使用新列表设置itemssource。
listbox.ItemsSource = null;
listbox.ItemsSource = yourUpdatedList;
模型类
public class MyClass:INotifyPropertyChanged
{
private List<Country> _countries = null;
public const string CountriesPropertyName = "Countries";
/// <summary>
/// Sets and gets the Countries property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public List<Country> Countries
{
get
{
return _countries;
}
set
{
if (_countries == value)
{
return;
}
_countries = value;
RaisePropertyChanged(CountriesPropertyName);
}
}
在您的page.xaml.cs
中var theModel =new MyModel();
theModel.Countries = yourcountryList;
上面的代码不是mvvm但它应该可以工作。
答案 1 :(得分:1)
如果您不想使用ObservableCollection(旨在处理此类任务),您可以构建自己的类并实施INotifyCollectionChanged Interface(即ObservableCollection
一样)。 Add
的简单示例如下所示:
public class ObsList<T> : List<T>, INotifyCollectionChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{ if (CollectionChanged != null) CollectionChanged(this, e); }
public new void Add(T item)
{
base.Add(item);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
}
然后在添加项目时更新ListBox:
// your list
private ObsList<string> ItemsList = new ObsList<string>();
// somewhere in constructor:
myListBox.ItemsSource = ItemsList;
// and add item anywhere:
ItemsList.Add("Added item");