如何将 WPF TreeView 绑定到 List以编程方式?
因此,我对 WPF 非常陌生,并尝试将 Drink 值列表绑定或分配给 wpf 树视图,但不知道如何执行此操作,并且发现很难在网上找到任何不使用 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 ) };
}
}
我怎样才能在代码中做到这一点?例如:
treeview1.DataItems = coldDrinks;
所有内容都显示在树视图中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以设置:
但是,我对这里使用 TreeView 提出疑问。显然,您显示的是平面的、非分层的数据,因此没有理由使用 TreeView。
为什么不直接使用 ListView 或 ListBox?
You can just set:
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?
里德说的话。另外:
您找不到编程示例的原因是这不太适合在代码中完成。正如里德所说,您设置了 ItemsSource 属性,但这并没有给出您正在寻找的结果。在您的示例中,输出将为:
这是因为默认项目模板仅显示项目的 ToString() 方法的结果。要获取饮料的名称,您需要指定自定义项目模板。这最好在 XAML 中完成。
您可以创建模板并将其附加到代码中,但这比在 XAML 中执行要花费更多的精力。
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:
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.
You can create the template and attach it in code, but it's a lot more effort than doing it in XAML.