如何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?