views:

147

answers:

2

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:

treeview1.DataItems = coldDrinks;

and everything shows up in the treeview.

+2  A: 

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?

Reed Copsey
You are right. I wanted to start with that, then move to hierarchical data :O. Another thing I am trying to do is to set the treeviewitem name to drink.Name. Can you please show me that too in code?
Joan Venge
It's much easier in XAML - basically, you need to setup a DataTemplate. If you really need a code sample, I'd ask it as a separate question, since it's too involved for a comment...
Reed Copsey
+1  A: 

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.

Scott J
Thanks, I just find it hard to understand xaml when migrating from winforms.
Joan Venge