我正在尝试绑定List<>到ListView。当我更新时,我要清除列表。在ObservableCollection上清除有点慢。 问题是在视图中事物没有正确更新。
XAML
<StackPanel.Resources>
<ResourceDictionary>
<common:BoolToBackgroundConverter x:Key="BoolToBackground"/>
<tb:StringInlineCollectionConvertor x:Key="InlineConvert"/>
</ResourceDictionary>
</StackPanel.Resources>
<ListView ItemsSource="{Binding NotificationsCollection, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
ScrollViewer.CanContentScroll="False">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Border>
<Grid Background="{Binding NotSeen,Converter={StaticResource BoolToBackground},UpdateSourceTrigger=PropertyChanged,NotifyOnSourceUpdated=True}">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Image Source="{Binding Thumb}"/>
<tb:BindableTextBlock InlineCollection="{Binding Text, Converter={StaticResource InlineConvert}}"/>
<TextBlock Text="{Binding Created}"/>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
C# 视图模型
public List<NotificationDataModel> notificationsCollection;
public List<NotificationDataModel> NotificationsCollection
{
get
{
if (notificationsCollection == null)
{
notificationsCollection = new List<NotificationDataModel>();
}
return notificationsCollection;
}
set
{
if (notificationsCollection == null)
{
notificationsCollection = new List<NotificationDataModel>();
}
notificationsCollection.Clear();
foreach (var item in value)
{
notificationsCollection.Add(item);
}
this.OnPropertyChanged("NotificationsCollection");
}
}
public void UpdateNotifications1()
{
List<NotificationDataModel> newCollection = new List<NotificationDataModel>();
newCollection.Add(item1);
newCollection.Add(item2);
newCollection.Add(item3);
newCollection.Add(item4);
newCollection.Add(item5);
newCollection.Add(item6);
this.NotificationsCollection = newCollection;
}
public void UpdateNotifications2()
{
List<NotificationDataModel> newCollection = new List<NotificationDataModel>();
newCollection.Add(item1);
newCollection.Add(item2);
newCollection.Add(item6);
this.NotificationsCollection = newCollection;
}
当我调用UpdateNotifications1时,元素会相应显示,但在此之后,当我调用UpdateNotifications2时,我会看到item1,item2和item3而不是item6。 关闭视图后,物品在NotSeen(例如黑色,初始为白色)属性中获得新值,重新打开时,这些项目应该是白色的,但它们仍然是黑色背景。
答案 0 :(得分:1)
问题是,当基础字段的实际值没有发生变化时,提升PropertyChanged
setter中的NotificationsCollection
事件无效。目标ItemsSource
属性接收相同的List实例(来自绑定),因此不会触发UI更新。
所以不要清除并复制到现有的集合,而是使用传递给setter的集合:
public List<NotificationDataModel> NotificationsCollection
{
get { return notificationsCollection; }
set
{
notificationsCollection = value;
OnPropertyChanged("NotificationsCollection");
}
}
答案 1 :(得分:0)
要么每次都创建一个新列表,要么使用像ObservableCollection&lt;&gt;
这样的东西