开发者

How to bind WPF TreeView to a List<Drink> programmatically?

开发者 https://www.devze.com 2022-12-23 18:53 出处:网络
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 online that just shows stuff wit

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 online that just shows stuff without using xaml.

struct Drink
{
    public string Name { get; private set; }
    public int Popularity { get; private set; }

    public Drink ( string name, int popularity )
        : this ( )
    {
        this.Name = name;
        this.Popularity = popularity;
    }
}

List<Drink> coldDrinks = new List<Drink> ( ){
    new Drink ( "Water", 1 ),
    new Drink ( "Fanta", 2 ),
    new Drink ( "Sprite", 3 ),
    new Drink ( "Coke", 4 ),
    new Drink ( "Milk", 5 ) };
        }
    }

How can I do this in code? For example:

treevie开发者_如何转开发w1.DataItems = coldDrinks;

and everything shows up in the treeview.


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?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号