XAML ListBox仅显示类名称

编程入门 行业动态 更新时间:2024-10-10 02:17:29
本文介绍了XAML ListBox仅显示类名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使我的班级属性显示在列表框中?

How do I get my class properties to show up in the ListBox?

XAML:

<ListBox x:Name="lstPlayers" > <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Player.FirstName}"></TextBlock> <TextBlock Text="{Binding Player.LastName}"></TextBlock> </StackPanel> </DataTemplate> </ListBox>

C#:

public class Player { string FirstName { get; set; } string LastName { get; set; } } public void LoadPlayers() { foreach (Player player in Players) { lstPlayers.Items.Add(player); } }

列表框中显示的唯一内容是

The only thing that shows up in the ListBox is

TestApplication1.Player

推荐答案

当前的实现存在一些问题.首先,应将DataTemplate放置在ListBox的ItemTemplate内.其次,每个ListBoxItem的DataContext将是Player的实例,因此您应直接绑定到FirstName和LastName.第三,应该公开Player中的属性,以便DataBinding起作用.

You have some problems with you current implementation. First, the DataTemplate should be placed inside the ItemTemplate for the ListBox. Second, the DataContext for each ListBoxItem will be an instance of Player so you should bind directly to FirstName and LastName. Third, the properties in Player should be made public for the DataBinding to work.

<ListBox x:Name="lstPlayers" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding FirstName}"></TextBlock> <TextBlock Text="{Binding LastName}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>

public class Player { public string FirstName { get; set; } public string LastName { get; set; } }

此外,无需将收集项逐项添加到ListBox,只需将其设置为ItemsSource

Also, instead of adding the collection item by item to the ListBox, just set it as ItemsSource

lstPlayers.ItemsSource = Players;

更多推荐

XAML ListBox仅显示类名称

本文发布于:2023-11-15 19:43:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1597403.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   XAML   ListBox

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!