开发者

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


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; }
}

Also, instead of adding the collection item by item to the ListBox, just set it as ItemsSource

lstPlayers.ItemsSource = Players;


DataTemplate should be inside ListBox.ItemTemplate.


set the collection, Players as ItemSource

and

<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>


you have to add the DataType to your DataTemplate.

<DataTemplate DataType="{x:Type local:Player}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding FirstName}"></TextBlock>
            <TextBlock Text="{Binding LastName}"></TextBlock>
        </StackPanel>
    </DataTemplate>

local is the namespace for your TestApplication1.Player. you can set the datatemplate to the listebox.itemtemplate or as a resource of any "parent object"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜