如何WPF TreeView控件绑定到一个List<饮料>编程? [英] How to bind WPF TreeView to a List<Drink> programmatically?

查看:886
本文介绍了如何WPF TreeView控件绑定到一个List<饮料>编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我很新的WPF和试图绑定或饮料值的列表分配到一个WPF树视图,但不知道该怎么做,并发现它真的很难在网上找到任何东西,只是显示的东西,而使用XAML。

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 ) };
        }
    }

我怎样才能做到这一点在code?例如:

How can I do this in code? For example:

treeview1.DataItems = coldDrinks;

和一切都显示在树视图。

and everything shows up in the treeview.

推荐答案

您可以只设置:

treeView1.ItemsSource = coldDrinks;

不过,我怀疑这里使用一个TreeView的。你显然呈现出平整,无分层数据,因此没有理由用一个TreeView。

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.

为什么不直接使用一个ListView或列表框?

Why not just use a ListView or ListBox?

这篇关于如何WPF TreeView控件绑定到一个List&LT;饮料&GT;编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆