【问题标题】:Change in Observable collection not reflected in UIObservable 集合的变化未反映在 UI 中
【发布时间】:2010-11-15 00:16:51
【问题描述】:

我有一个属性 o 类型“可观察的集合”...当我添加一个项目时它没有反映在 UI 中...做错了什么...?

<ComboBox Grid.Column="0" Grid.Row="3" 
Width="120" SelectedIndex="0"
Margin="5,0,0,0" HorizontalAlignment="Left"
ItemsSource="{Binding AllPlaces}" 
DisplayMemberPath="PlaceName" 
SelectedItem="{Binding Path=SelectedPlace.Value, Mode=TwoWay}" 
VerticalAlignment="Top">
</ComboBox>


// Add the new item to the existing place list, so that it will be refreshed.
ObservableCollection<PlaceDto> existingPlaceList = new ObservableCollection<PlaceDto>();
// Copy all places to a temperory list.
foreach(PlaceDto placeItem in AllPlaces)
{
existingPlaceList.Add(placeItem);
}
// Add new place to existing list
existingPlaceList .Add(newPlace);
AllPlaces= existingPlaceList;

【问题讨论】:

  • 请在 xaml 中显示绑定并添加一个元素。
  • 为什么要将所有地点复制到临时列表中?只需将该地点添加到 AllPlaces。 AllPlaces.Add(newPlace)。其余的都不需要。并在构造函数中初始化 AllPlaces 变量。

标签: wpf data-binding observablecollection


【解决方案1】:

如果列表发生变化,ObservableCollection 将通知 GUI。但是,您正在使用 AllDivisions = existingPlaceList 行更改整个列表本身。您必须为包含 AllDivisions 属性的类实现 INotifyPropertyChanged,以便在您换出列表时通知 GUI。

【讨论】:

  • 绝对正确。他应该添加到现有的 observablecollection 中。更改参考将不起作用。
  • 我只是想将新项目添加到列表中。如果我只使用这一行 => AllPlaces.Add(newPlace);.. 它会起作用吗?
  • @Anish:删除 AllPlaces= existingPlaceList 分配,并将 AllPlaces 用作公共属性,并带有返回 existingPlaceList 的 getter,如果您必须清空它,请使用 Clear() 将现有 PlaceList 设为类实例变量而不是每次都创建一个新列表。
猜你喜欢
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 2014-03-29
  • 2018-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-07
相关资源
最近更新 更多