[英]XAML ListBox only shows class name
如何获得我的班级属性以显示在列表框中?
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);
}
}
列表框中显示的唯一内容是
TestApplication1.Player
您当前的实现存在一些问题。 首先,DataTemplate中应放置在里面的ItemTemplate为ListBox
。 其次,每个ListBoxItem
的DataContext将是Player
一个实例,因此您应直接绑定到FirstName
和LastName
。 第三,应该公开Player
的属性以使DataBinding起作用。
<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
lstPlayers.ItemsSource = Players;
DataTemplate应该在ListBox.ItemTemplate内部。
设置集合,玩家作为ItemSource
和
<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>
您必须将DataType添加到您的DataTemplate中。
<DataTemplate DataType="{x:Type local:Player}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}"></TextBlock>
<TextBlock Text="{Binding LastName}"></TextBlock>
</StackPanel>
</DataTemplate>
local是您的TestApplication1.Player的名称空间。 您可以将datatemplate设置为listebox.itemtemplate或作为任何“父对象”的资源
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.