[英]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.