I have a TreeView that is bound to an ObservableCollection in my ViewModel. I have an issue where if I add an item to the ObservableCollection, sometimes it isn’t displayed in the GUI.
I have debugged and found that the item indeed gets added and the CollectionChanged event does indeed get fired on the observable collection. Other parts of my GUI even update to reflect the newly added and selected item. The only problem is that the new item does not show up in the TreeView.
It’s a bit strange because sometimes it will show up, sometimes it will flicker up then go away, and sometimes it won’t show up at all. Any ideas?
EDIT:
TreeView XAML:
<TreeView Name="cedarTreeView"
ItemsSource="{Binding CurrentFiles}"
ItemTemplate="{StaticResource MyFileTemplate}"
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Recycling">
<TreeView.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</TreeView.ItemsPanel>
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="FontSize" Value="12" />
<Setter Property="AllowDrop" Value="True" />
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
The DataTemplate:
<HierarchicalDataTemplate x:Key="MyFileTemplate"
ItemTemplate="{StaticResource QualifierTemplate}"
ItemsSource="{Binding Qualifiers, Converter={StaticResource SortByNameConverter}}">
<HierarchicalDataTemplate.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="Visibility" Value="{Binding IsVisible, Converter={StaticResource BoolToVisConverter}}" />
</Style>
</HierarchicalDataTemplate.ItemContainerStyle>
<TextBlock Text="{Binding Name, Mode=OneWay}" ToolTip="{Binding Name, Mode=OneWay}" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=TreeView}}">
<TextBlock.ContextMenu>
Some Context Menu Stuff Here
</TextBlock.ContextMenu>
</TextBlock>
</HierarchicalDataTemplate>
I am adding to the Qualifiers ObservableCollection. It displays them fine when I first open the file and add all of the existing ones. The problem is when i try to create a new one.
Are you perhaps modifying the collection from a separate thread or task?