我在 ViewModel 中有一个 ObservableCollection,当在 View 中按下 ApplicationBar 按钮时,它会添加新条目。绑定(bind)到此 ObservableCollection 的 ListBox 不会显示新的/更新的条目,它会在应用程序加载时显示集合的项目。 ViewModel 确实实现了 INotifyPropertyChanged,并且当将项目添加到 ObservableCollection(或)集中时,我确实调用了 NotifyPropertyChanged。
ViewModel - 根据从服务器读取的内容,新项目将添加到可观察集合中。
public class MainViewModel : INotifyPropertyChanged
{
private ObservableCollection<SubsViewModel> _itemsUnread;
public ObservableCollection<SubsViewModel> UnreadItems
{
get
{
return _itemsUnread;
}
set
{
_itemsUnread = value;
NotifyPropertyChanged("Updated");
}
}
void reader_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "Updated":
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
UnreadItems.Clear();
foreach (ItemViewModel subs in ItemsAll)
{
....
UnreadItems.Add(subs);
}
}
);
IsDataUpdated = true;
NotifyPropertyChanged(e.PropertyName);
break;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
if (null != this.PropertyChanged)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
View - 设置数据上下文和项目源
<ListBox x:Name="SecondListBox" Margin="0,0,-12,0" ItemsSource="{Binding UnreadItems, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,7">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ItemTitle}" TextWrapping="NoWrap" Margin="12,0,0,0" Style="{StaticResource PhoneTextLargeStyle}"/>
...
public MainPage()
{
_mainView = new MainViewModel();
InitializeComponent();
// Set the data context of the listbox control to the sample data
DataContext = _mainView;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
对 viewModel 中可观察集合的任何添加/更新都不会反射(reflect)在列表框中。我读过很多地方,notifypropertychanged 是解决方案,但我已经有notifypropertychanged 并且仍然看到问题。我缺少什么想法吗?
来自@compoenet_tech的建议 通过在按下 ApplicationBar 按钮时添加新项目。我确实看到列表框显示了新项目
SubsViewModel newitem = new SubsViewModel();
newitem.itemTitle = "test";
newitem.itemCount = test;
_itemssUnread.Add(newitem); test++;
因此,在调度程序调用之外执行 Add() 确实有效。但现在的问题是我使用回调从 web 服务获取新列表,这是我将条目添加到未读项目集合中的地方。我不能(?)在调度员之外做这件事。
(web service) =callback=> ViewModel =observablecollection=> View
viewmodel 如何收到通知以在回调之外更新集合,而我不必使用 dispather 调用? (或)使用调度程序调用而不是通过跨线程引用崩溃。
谢谢
最佳答案
请在使用前实例化 Observable 集合。 在
MainViewModel
的构造函数中编写以下代码,如公共(public)MainViewModel() { _itemsUnread = new ObservableCollection(); }
不需要实现函数
reader_PropertyChanged
。调用
NotifyPropertyChanged
时,使用属性名称作为参数,例如公共(public) ObservableCollection 未读项目 { 得到 { 返回_itemsUnread; } 放 { _itemsUnread = 值; NotifyPropertyChanged("未读项目"); } }
关于.net - 添加后,Windows Phone MVVM 中 ListBox DataBound 到 ObservableCollection 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8582717/