【发布时间】:2015-07-16 11:58:46
【问题描述】:
我有一个带有可观察集合属性的 ViewModel
public ObservableCollection<GeographicArea> CurrentSensorAreasList
{
get
{
return currentSensorAreasList;
}
set
{
if (currentSensorAreasList != value)
{
currentSensorAreasList = value;
OnPropertyChanged(PROPERTY_NAME_CURRENT_SENSOR_AREAS_LIST);
}
}
}
然后在我的 xaml 中我有一个绑定
ItemsSource="{绑定 CurrentSensorAreasList}">
这个 Observable Collection 是通过一个可以在 viewModel 构造函数中调用的方法或当另一个列表中的 collectionchanged 处理程序被调用时更新的。
我只是清除列表,然后添加更少的新项目。在调试时,我看到列表中的所有新项目都已更新。但是 UI 没有得到更新。 当我重新生成 viewModel 然后在构造函数中调用此更新方法时,列表会在 UI 中更新。
有什么想法吗??我不知道当我从处理程序调用方法时是否出现问题.....
更新 #1
根据要求,当我更新列表时,我将使用代码 我已经测试了两种方法来进行此更新
private void UpdateList1()
{
if (globalAreaManagerList != null && OperationEntity != null)
{
CurrentSensorAreasList.Clear();
CurrentSensorAreasList.AddRange(globalAreaManagerList.Where(x => x != (OperationEntity as AreaManager)).SelectMany(areaRenderer => areaRenderer.AreaList));
//AddRange 是一个扩展方法。
}
}
private void UpdateList2()
{
if (globalAreaManagerList != null && OperationEntity != null)
{
CurrentSensorAreasList = new ObservableCollection<GeographicArea>(globalAreaManagerList.Where(x => x != (OperationEntity as AreaManager)).SelectMany(areaRenderer => areaRenderer.AreaList))
}
}
当我从构造函数调用它时,这两种情况都有效。然后我有其他区域发生变化的列表,我通过 CollectionChanged 处理程序得到通知。
private void globalAreaManagerList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (AreaManager newItem in e.NewItems)
{
newItem.AreaList.CollectionChanged += AreaList_CollectionChanged;
}
}
if (e.OldItems != null)
{
foreach (AreaManager oldItem in e.OldItems)
{
oldItem.AreaList.CollectionChanged -= AreaList_CollectionChanged;
}
}
UpdateList();
}
private void AreaList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
UpdateList();
}
因此,当我使用 UpdateList1 时,它似乎可以工作更多次,但突然绑定被破坏,然后此更新不会显示在 UI 中。
【问题讨论】:
-
看起来一切正常。请在您更新集合的位置显示代码。
-
我把代码放在我更新列表的地方。这似乎很奇怪,因为有时有效,而另一些则无效...
标签: wpf binding observablecollection