I have a TreeView control in my application that is populated (in the XAML) by binding its ItemsSource to an ObservableCollection of strings in my view model. There are many more nodes that can be viewed within the TreeView, so it displays a scroll bar to allow vertical scrolling. However, when I programmatically request the IsVisible property of individual TreeViewItems in my code-behind, all of them return True, regardless of whether they are actually visible or not.
XAML:
<Grid Margin="10">
<Grid.DataContext>
<local:NodeViewModel/>
</Grid.DataContext>
<TreeView Name="filterTree" ItemsSource="{Binding Path=NodeList, Mode=OneWay }" />
</Grid>
ViewModel:
class NodeViewModel
{
public ObservableCollection<string> NodeList { get; private set; }
public NodeViewModel()
{
NodeList = new ObservableCollection<string>();
for ( int i = 0; i < 25; i++ ) {
NodeList.Add($"{i}");
}
}
}
Code-behind:
private void Window_ContentRendered(object sender, System.EventArgs e)
{
foreach ( string node in filterTree.Items ) {
TreeViewItem item = filterTree.ItemContainerGenerator.ContainerFromItem(node) as TreeViewItem;
System.Diagnostics.Debug.WriteLine($"Node {node} is {(item.IsVisible ? "visible" : "hidden")}");
}
}
Although the window is only large enough to display the first 10 nodes, all 25 nodes in the collection print out as "visible" in the diagnostic output.
Any ideas?