C#C
C#15mo ago
Saiyanslayer

WPF TreeView Fails to load ItemsSource

The control

<UserControl x:Class="XMLViewer.Features.XMLViewer.XmlViewerComponent"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:XMLViewer.Features.XMLViewer" 
             mc:Ignorable="d" 
             d:DataContext="{d:DesignInstance Type=local:XmlViewerViewModel}"
             d:DesignHeight="600" d:DesignWidth="400" >
    
    <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden">
        <StackPanel Orientation="Vertical">
            <TextBlock Text="{Binding Items.Name}" />
            <TreeView ItemsSource="{Binding Items}" Height="300">
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate DataType="{x:Type local:NodeItem}" ItemsSource="{Binding Children}">
                        <TextBlock Text="{Binding Name}" />
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>
            </TreeView>
            <TextBlock Text="{Binding Text}" Foreground="Gray"/>
        </StackPanel>
    </ScrollViewer>

</UserControl>


The viewmodel:
namespace XMLViewer.Features.XMLViewer;
public partial class XmlViewerViewModel : ObservableObject {
    [ObservableProperty]
    public NodeItem _items;

    public XmlViewerViewModel() {
        //testing treeview binding
        var test = new NodeItem {
            Name = "Test 1",
            Children = new ObservableCollection<NodeItem> {
            new NodeItem {Name = "Test 1.1" },
            new NodeItem { Name = "Test 1.2" },
        },
        };

        Items = test;
    }

}
Was this page helpful?