I
I
IvankoPo2018-10-29 19:52:11
Microsoft
IvankoPo, 2018-10-29 19:52:11

How to use the DataBinding of a TreeView in UWP?

In the project, you need to bind the TreeView to the model.
Windows 10 1803
VS 2017
Project on UWP
Initially, the TreeView element did not have the ItemsSource property Googled
and connected these packages https://docs.microsoft.com/en-us/uwp/toolkits/winu ... I use an example from here https://docs.microsoft.com/en-us/windows/uwp/desig... Model

public class Item
    {
        public string Name { get; set; }
        public ObservableCollection<Item> Children { get; set; } = new ObservableCollection<Item>();

        public override string ToString()
        {
            return Name;
        }
    }

TreeView element with element template
<controls:TreeView Name="DessertTre" Width="300"
                      SelectionMode="Multiple"
                      ItemsSource="{x:Bind dataSource}">
                    <controls:TreeView.ItemTemplate>
                        <DataTemplate x:DataType="local:Item">
                            <controls:TreeViewItem ItemsSource="{x:Bind Children}"
                                      Content="{x:Bind Name}"/>
                        </DataTemplate>
                    </controls:TreeView.ItemTemplate>
                </controls:TreeView>

Data source initialization
public sealed partial class MainPage : Page
    {
        private ObservableCollection<Item> dataSource = new ObservableCollection<Item>();

        public MainPage()
        {
            this.InitializeComponent();
            
            Item flavorsCategory = new Item()
            {
                Name = "Flavors",
                Children =
                {
                    new Item() { Name = "Vanilla" },
                    new Item() { Name = "Strawberry" },
                    new Item() { Name = "Chocolate" }
                }
            };
            dataSource.Add(flavorsCategory);


        }

Testing
Firstly, there is no arrow for child elements, secondly, a bug in displaying an incomprehensible area when hovering over with the mouse . On the 5bd73ab1aaa9e281701685.png
left, a TreeView with chord-coded elements in XAML
. In the center, under the slider, what I tried to do using databinding

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question