I need to show constants, which are based on other constants, in a TreeView but can't get it working. I already searched for an answer and tried to implement something similar to the tutorials I've found so far.
My aim is to show a TreeView (with dummy data for now) like this:
c1 (Parent)
c3 (Child)
c2 (Parent)
c4 (Child)
c5 (Child)
My code looks like this (it's without the data I'm going to process later)
MainViewModel
{
internal class MVM : INotifyPropertyChanged
{
public static ObservableCollection<Const> constants = new ObservableCollection<Const>();
public event PropertyChangedEventHandler PropertyChanged;
public MVM()
{
Const c1 = new Const("ABL", null);
Const c2 = new Const("ASL", null);
Const c3 = new Const("BBL", c1);
Const c4 = new Const("BSL", c2);
Const c5 = new Const("CBL", c2);
constants.Add(c1);
constants.Add(c2);
c1.setChildren(new List<Const> { c3 });
c2.setChildren(new List<Const> { c4, c5 });
OnPropertyChange(nameof(constants));
}
protected void OnPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
MainWindow.xaml header
<Window x:Class="ConstSearch.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ConstSearch"
xmlns:vm="clr-namespace:ConstSearch"
mc:Ignorable="d"
Title="ConstSearch" Height="450" Width="450" MinHeight="450" MinWidth="450">
<Window.DataContext>
<vm:MVM/>
</Window.DataContext>
MainWindow.xaml TreeView
<TreeView x:Name="constOutput" Margin="25,76,25,0" Height="130" HorizontalAlignment="Stretch" VerticalAlignment="Top" ItemsSource="{Binding constants}"><!--Style="{StaticResource lightGrayTV}"-->
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Const}" ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Path=Name}"/>
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Const}" ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
Const.cs Model
namespace ConstSearch
{
class Const
{
public string Name { get; set; }
public Const Parent { get; set; }
public List<Const> Children { get; set; }
public Const(string name, Const con)
{
Name = name;
Parent = con;
}
public void setChildren(List<Const> children)
{
Children = children;
}
public override string ToString()
{
return $"Name: {Name}";
}
}
}
Thank you for your help in advance!