如何使我的班级属性显示在列表框中?
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仅显示类名称
发布评论