I've looked around a bit, but I'm not understanding some of the answers which is why I'm asking here.
I'm trying to populate a Treeview with a code-first database as setup with Entity Framework 6. It's an (I think) pretty straightforward parent-child relationship. 1 parent entity can have multiple children. I'd like a Treeview with this relationship displayed. Expand a parent entity and the right children will show. The Treeview is showing records, but it's not what is in the database. Datacontext is managed by using a locator class. But the datatype property of the Treeview is not picking up where to be as well. (Side note that other parts that are defined in the viewmodel do get picked up on, so I don't think it's that connection)
Does anyone know where things could be going wrong? My code is
private void SetInitialSettings()
{
AllParentsToList.Clear();
foreach (var item in ParentList()) AllParentsToCollection.Add(item);
}
public ObservableCollection<Parent> AllParentsToCollection{ get; } = new ObservableCollection<Parent>();
public static List<Parent> ParentList()
{
using (var context = new EFContext())
{
return context.Parents
.Select(p => p)
.Include(p => p.Children)
.ToList();
}
}
The xaml code (including locator)
DataContext = "{Binding View1, Source={StaticResource Locator}}"
<TreeView ItemsSource="{Binding ParentsToCollection}"
Grid.Column="1"
Grid.Row="3"
Grid.RowSpan="6" >
<TreeView.Resources>
<HierarchicalDataTemplate
ItemsSource="{Binding AllParentsToCollection}"
DataType="{x:Type View1:Parent}">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Name}"
Foreground="Black" />
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type View1:Child}">
<Label Content="{Binding Path=Name}"
Foreground="Black" />
</DataTemplate>
</TreeView.Resources>
</TreeView>
And the datamodel class, which is also my first time setting up an Entity database
public class Parent : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public int ParentID { get; set; }
public string Name { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class Child : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public int ChildID { get; set; }
public string Name { get; set; }
public int ParentID { get; set; }
public Parent Parent { get; set; }
}
What I have tried:
Various tutorials, none seem to work