我的列表框没有更新
本文关键字:更新 列表 我的 | 更新日期: 2023-09-27 18:12:27
我有一个列表框,我绑定HistoryItems
,其中HistoryItems
是History
的ObservableCollection
。下面是列表框的声明:
<ListBox x:Name="RecentListBox" SelectionChanged="RecentListBox_SelectionChanged" ItemsSource="{Binding HistoryItems,Converter={StaticResource HistoryValueConverter} }" ItemsPanel="{StaticResource ItemsPanelTemplate1_Wrap}" ItemTemplate="{StaticResource RecentViewModelTemplate}">
下面是History
类:
public class History : INotifyPropertyChanged
{
public History() { }
int _id;
string _date;
string _url;
string _name;
public History(int id, string date,string url,string name)
{
this.id = id;
this.date = date;
this.url = url;
this.name = name;
}
public int id
{
get
{
return _id;
}
set
{
if (value != _id)
{
_id = value;
NotifyPropertyChanged("id");
}
}
}
public string date
{
get
{
return _date;
}
set
{
if (!value.Equals(_date))
{
_date = value;
NotifyPropertyChanged("string");
}
}
}
public string url
{
get
{
return _url;
}
set
{
if (!value.Equals(_url))
{
_url = value;
NotifyPropertyChanged("url");
}
}
}
public string name
{
get
{
return _name;
}
set
{
if (!value.Equals(_name))
{
_name = value;
NotifyPropertyChanged("name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
// App.viewModel.HistoryItems = (App.Current as App).dataHandler.retrieveHistory_DB();
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
当我启动应用程序的列表得到填充,但我做了一些修改后,在一些枢轴子,并回到主全景视图,我尝试更新OnNavigatedTo
中的HistoryItems
:
App.ViewModel.HistoryItems = (App.Current as App).dataHandler.retrieveHistory_DB();
,但列表框没有更新(函数返回正确的数据)。问题是什么呢?History
是INotifyPropertyChanged
, HistoryItems
是ObservableCollection<History>
,所以应该没有问题。是什么原因导致列表不更新?
既然你是替换HistoryItems
当你刷新它并不重要,它是一个ObservableCollection
。
您可以清除HistoryItems
,然后在刷新时添加新项目。或者ViewModel
应该实现INotifyPropertyChanged
, HistoryItems
setter应该引发事件。
为ViewModel重写setter。而不是这样做
_historyItems = value;
它做这个
if (_historyItems == null)
_historyItems = new ObservableCollection<HistoryItem>();
_historyItems.Clear();
foreach (var hi in value)
_historyItems.Add(hi);
在HistoryItems
的Setter中需要NotifyPropertyChanged
代替App.ViewModel