It has been while since I worked with XAML on a regular basis and I am struggling with the basics.
I am trying to show items in an ItemsControl
like so:
<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>
The ViewModel is just as basic:
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
is a custom type which synchs with the underlying collection of models automatically. I've used this for years in all types of scenarios with no problems.
However, in the view, the items don't show up and I get a weird behavior which I cannot explain:
- The text block bound to
ProfilePages.Count
works as expected, i.e. the number showing up is the number of items in the list. - No binding errors
- The
CollectionChanged
event of theProfilePages
-collection is fired correctly - Also adding a
RaisePropertyChanged
-event for the entire collection property in theCollectionChanged
event handler doesn't change the behavior - The get accessors of the
ProfilePages
property is called twice as expected in the previous sceanrio (firingRaisePropertyChanged
) - When I edit the XAML while debugging, sometimes items show up in the
ItemsControl
as expected. The list of items doesn't update afterwards, however
I cannot explain the behavior and have no idea, what the issue is. I have checked the common troubles (wrong definition of ItemTemplate
, missing CollectionChanged
event, layout bugs causing items to render invisibly, etc. with no success).
How can this behavior be explained? How can it be fixed?