Blank空白 Blank空白 - 1 month ago 10
C# Question

Adding custom class elements into TreeView

I will try to explain what I've been trying to do and couldn't figure it out as simple as possible (using cars for example). Let's say that I have a custom made class (which could also have more than three elements) in my MainWindw.xaml.cs code:

public class Car {
public string car_name { get; set; }
public string car_brand { get; set; }
public int car_year { get; set; }
}


Now I would like to implement Car into a TreeView, which should look something like this:

->car_name
->car_brand
->car_year


So when I click on car_name, it expands and car_brand and car_year are it's sub elements. I also want to be able to add multiple of those, e.g.:

->car_name
->car_brand
->car_year
->car_name
->car_brand
->car_year
->car_name
->car_brand
->car_year


What I can not figure out is what is the proper way of implementing my custom made class into TreeView using C#. I have tried many variants of "Binding". There are numerous examples on the internet, but I haven't come across any which would be really simplified, or I've been looking at this for too long and gone a bit mad and unable to see through it.

<TreeView Name="myTree">
<TreeViewItem Header="{Binding car_name}">
<TreeViewItem Header="{Binding car_brand}"/>
<TreeViewItem Header="{Binding car_year}"/>
</TreeViewItem>
</TreeView>


C# as I imagine it should go something like this when I want to add a new car:

Car mycar1 = new Car({car_name="my car name", car_brand="my car brand", car_year=1999});
myTree.Add(mycar1);


I would love it if anyone could explain this to me in simple terms. I just started learning C# and XAML using VisualStudio and it is really bugging me.

Answer

It can be simply done this way without the Binding:

           Car mycar1 = new Car("my car name", "my car brand", 1999);
           TreeViewItem node = new TreeViewItem() { Header = mycar1.car_name};
           node.Items.Add(new TreeViewItem() { Header = mycar1.car_brand });
           node.Items.Add(new TreeViewItem() { Header = mycar1.car_year });
           myTree.Items.Add(node);

every node is the car name and to the node you add the brand and year and then add the whole node to the tree like done above. note this is the Car class I used:

public class Car
{
    public string car_name { get; set; }
    public string car_brand { get; set; }
    public int car_year { get; set; }
    public Car(string name, string brand, int year)
    {
        car_brand = brand;
        car_name = name;
        car_year = year;
    }
}