XAML ListBox仅显示类名称 [英] XAML ListBox only shows class name
问题描述
如何使我的班级属性显示在列表框中?
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仅显示类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!