79699578

Date: 2025-07-12 20:50:15
Score: 0.5
Natty:
Report link

Instead of using the TreeViewItem class of objects I ended up just creating the following class:

using System.Collections.ObjectModel;

namespace Custom_XML_Editor.Models
{
    public class TreeNode
    {
        public string Header
        {
            get; 
            set;
        }
        public ObservableCollection<TreeNode> Children
        {
            get; 
            set;
        }
        public TreeNode(string header)
        {
            Header   = header;
            Children = new();
        }
    }
}

Then modifying the XAML:

<UserControl x:Class="Custom_XML_Editor.Views.XMLTreeView"
             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:Custom_XML_Editor.Views"
             xmlns:models="clr-namespace:Custom_XML_Editor.Models"
             mc:Ignorable="d" 
             d:DesignHeight="450" 
             d:DesignWidth="800">
    <Grid>
        <TreeView ItemsSource="{Binding Root}"
                  Grid.Row="1">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate DataType="{x:Type models:TreeNode}"                 
                                          ItemsSource="{Binding Children}">
                    <TextBlock Text="{Binding Header}"/>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </Grid>
</UserControl>

It seems silly that using the TreeViewItems class is.... impossible(?) to add items to a TreeView pragmatically from a ViewModel, but a generic class you throw together in 20 seconds works just fine.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Ben