2011-03-10 21 views
1

如何讓我的班級屬性顯示在列表框中?XAML列表框只顯示班級名稱

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 

回答

8

您在目前的實施中遇到了一些問題。首先,DataTemplate應放置在ListBox的ItemTemplate中。其次,每個ListBoxItem的DataContext將是Player的一個實例,因此您應該直接綁定到FirstNameLastName。第三,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; 
+0

+1對於第二點,我看不到因爲在iPhone上StackOverflow不顯示滾動代碼部分,我只能看到「 {綁定「... – 2011-03-10 10:13:52

+1

@Akash Kava:我一直在iPhone上遇到同樣的問題,但我最近注意到,如果您用兩個手指點擊/按下代碼,則可以滾動它。試試吧:) – 2011-03-10 10:18:26

+0

非常感謝,它的作品,太糟糕了直到約會沒有人告訴我! – 2011-03-10 11:03:17

1

的DataTemplate應該是內部ListBox.ItemTemplate 。

1

設置的集合,球員的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> 
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的命名空間。你可以將數據模板設置爲listebox.itemtemplate或作爲任何「父對象」的資源