【发布时间】:2019-03-18 10:05:12
【问题描述】:
自从我定期使用 XAML 以来已经有一段时间了,我一直在努力学习基础知识。
我正在尝试在 ItemsControl 中显示项目,如下所示:
<DockPanel DockPanel.Dock="Left" Width="800">
<TextBlock DockPanel.Dock="Top" Text="{Binding ProfilePages.Count}"></TextBlock>
<Grid>
<ItemsControl ItemsSource="{Binding ProfilePages}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="Hello World" Height="100" Width="200" Background="AliceBlue"></TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</DockPanel>
ViewModel 也一样基本:
public class XtmProjectViewModel : NotifyingObject
{
private ViewModelCollection<XtmProfilePageViewModel, XtmProfilePage> _profilePages;
public ViewModelCollection<XtmProfilePageViewModel, XtmProfilePage> ProfilePages
{
get { return _profilePages; }
set
{
_profilePages = value;
RaisePropertyChanged(() => ProfilePages);
}
}
public ViewModelCollection<XtmSearchPageViewModel, XtmSearchPage> SearchPages { get; }
public XtmProjectViewModel(XtmProject model)
{
ProfilePages = new ViewModelCollection<XtmProfilePageViewModel, XtmProfilePage>(model.ProfilePages, s => new XtmProfilePageViewModel(s));
SearchPages = new ViewModelCollection<XtmSearchPageViewModel, XtmSearchPage>(model.SearchPages, s => new XtmSearchPageViewModel(s));
ProfilePages.CollectionChanged += ProfilePages_CollectionChanged;
}
private void ProfilePages_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
Console.WriteLine("Test");
RaisePropertyChanged(() => ProfilePages);
}
}
ViewModelCollection 是一种自定义类型,可自动与底层模型集合同步。我已经在所有类型的场景中使用它多年了,没有任何问题。
但是,在视图中,这些项目没有出现,我得到了一个我无法解释的奇怪行为:
- 绑定到
ProfilePages.Count的文本块按预期工作,即显示的数字是列表中的项目数。 - 没有绑定错误
-
ProfilePages-collection 的CollectionChanged事件被正确触发 - 同时在
CollectionChanged事件处理程序中为整个集合属性添加RaisePropertyChanged-事件不会改变行为 -
ProfilePages属性的 get 访问器在之前的场景中被调用两次(触发RaisePropertyChanged) - 当我在调试时编辑 XAML 时,有时项目会按预期显示在
ItemsControl中。但是,项目列表不会在之后更新
我无法解释这种行为,也不知道问题是什么。我检查了常见的问题(ItemTemplate 的错误定义、缺少CollectionChanged 事件、导致项目不可见呈现的布局错误等没有成功)。
如何解释这种行为? 怎么解决?
【问题讨论】:
-
想知道您是否在 UI 线程上将对象插入 ProfilePagesnot。
-
我的第一个想法是
ViewModelCollection不是IEnumerable类型?但是你说它有时会显示项目。您是否尝试过在 XAML 中使用CollectionViewSource?您还可以创建临时集合,然后将其分配给您的ProfilePages属性。 -
@kenny 那是真的,谢谢!!
-
@kenny 随时回复!我会删除我的并标记为已解决!
-
@Marc 不客气。将其推送到答案。
标签: wpf xaml itemscontrol