I want to make an application in .NET MAUI that allows users to create and visualize family trees. Here is my Person class:
public class Person
{
public string Name;
public List<Person> Children { get; set; } = new List<Person>();
public List<Person> Spouses { get; set; } = new List<Person>();
public string SortValue;
public string ImagePath;
public Person(string name, string sortValue, string imagePath)
{
Name = name;
SortValue = sortValue;
ImagePath = imagePath;
}
}
Because I'm working in MAUI, a way to display the family tree in XAML would be best. If I were to create a family in my code and then run in, I would like the structure to look like a traditional family tree, something like this:
Right now, I have a RenderFamilyTree
method that looks like this:
private void RenderFamilyTree(Person person, StackLayout container)
{
var personBox = new StackLayout
{
BackgroundColor = Colors.LightBlue,
WidthRequest = 100,
HeightRequest = 100,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Padding = 5,
Children =
{
new Label
{
Text = person.Name,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
TextColor = Colors.Black,
}
}
};
foreach (var spouse in person.Spouses)
{
personBox.Children.Add(new Label
{
Text = $"Spouse: {spouse.Name}",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
TextColor = Colors.DarkBlue,
});
}
container.Children.Add(personBox);
foreach (var child in person.Children)
{
var childContainer = new StackLayout();
container.Children.Add(childContainer);
var connector = new BoxView
{
Color = Colors.Red,
HeightRequest = 20,
WidthRequest = 1,
};
container.Children.Add(connector);
RenderFamilyTree(child, childContainer);
}
}
This is using a Vertical StackLayout so I can't get horizontal boxes to represent spouses and siblings. And right now spouses are both put in one box instead of one for each of them. In the XAML file, I have:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:FamilyTreeApp"
x:Class="FamilyTreeApp.MainPage">
<ScrollView>
<StackLayout x:Name="FamilyTreeStackLayout" HorizontalOptions="CenterAndExpand">
<!--Family tree will be dynamically generated here-->
</StackLayout>
</ScrollView>
</ContentPage>
I have thought about using a Grid layout but am not sure about how I would connect each box, because the lines connecting them would all be different based on which level they are on, the relationship between boxes, and how many boxes come from another box. How can I modify my RenderFamilyTree
method to correctly place horizontal entries for spouses and siblings, as well as draw appropriate lines connecting them?