如何让我的类属性显示在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);
}
}
ListBox中唯一显示的是
TestApplication1.Player
答案 0 :(得分:8)
您当前的实施遇到了一些问题。首先,DataTemplate应该放在ListBox
的ItemTemplate中。其次,每个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;
答案 1 :(得分:1)
DataTemplate应该在ListBox.ItemTemplate中。
答案 2 :(得分:1)
设置集合,Players as ItemSsource
和
<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>
答案 3 :(得分:0)
您必须将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或任何“父对象”的资源