How to bind WPF TreeView to a List programmatically?

后端 未结 2 741
灰色年华
灰色年华 2021-01-07 08:16

So I am very new to WPF and trying to bind or assign a list of Drink values to a wpf treeview, but don\'t know how to do that, and find it really hard to find anything onlin

相关标签:
2条回答
  • 2021-01-07 08:21

    You can just set:

    treeView1.ItemsSource = coldDrinks;
    

    However, I question the use of a TreeView here. You're obviously showing flat, non-hierarchical data, so there is no reason to use a TreeView.

    Why not just use a ListView or ListBox?

    0 讨论(0)
  • 2021-01-07 08:31

    What Reed said. Plus:

    The reason you're not finding programmatic examples is this isn't well suited to being done in code. As Reed said, you set the ItemsSource property, but that doesn't give the results you're looking for. In your example the output will be:

    MyApplication.Drink
    MyApplication.Drink
    MyApplication.Drink
    MyApplication.Drink
    MyApplication.Drink
    

    This is because the default item template simply displays the results of the ToString() method of the item. To get the names of the drinks you need to specify a custom item template. This is best done in XAML.

        <TreeView x:Name="treeView1">
            <TreeView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" />
                </DataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    

    You can create the template and attach it in code, but it's a lot more effort than doing it in XAML.

    0 讨论(0)
提交回复
热议问题