【发布时间】:2012-01-24 20:17:45
【问题描述】:
我在 ViewModel 中有一个 ObservableCollection,当在 View 中按下 ApplicationBar 按钮时,它会添加新条目。绑定到此 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 - 设置 datacontext 和 itemsource
<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 中的 observablecollection 的任何添加/更新都不会反映在列表框中。我已经阅读了很多地方, notifypropertychanged 是解决方案,但我已经 notifypropertychanged 并且仍然看到问题。任何想法我错过了什么?
来自@compoenet_tech 的建议 通过在按下 ApplicationBar 按钮时添加新项目。我确实看到列表框显示了新项目
SubsViewModel newitem = new SubsViewModel();
newitem.itemTitle = "test";
newitem.itemCount = test;
_itemssUnread.Add(newitem); test++;
因此,在 Dispatcher Invoke 之外执行 Add() 确实有效。但现在的问题是我使用回调从 web 服务获取新列表,这是我将条目添加到 unreaditems 集合的地方。我不能(??)在调度员之外做。
(web service) =callback=> ViewModel =observablecollection=> View
如何通知 viewmodel 在我不必使用 dispather 调用的回调之外更新集合? (或)使用调度程序调用而不是通过跨线程引用崩溃。
谢谢
【问题讨论】:
-
在您的 UnreadItems 属性设置器中,您为“更新”命名属性提出了 NotifyPropertyChanged,您应该为 UnreadItems 提出它。至少我认为这是问题所在。
-
我现在明白你为什么用 Update 调用它了,也许这是你处理属性更改事件的问题,所以它没有到达 UI。
标签: .net windows-phone-7 data-binding listbox observablecollection