Jack B Nimble
Jack B Nimble

Reputation: 5087

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

Upvotes: 1

Views: 4290

Answers (4)

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84674

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;

Upvotes: 9

blindmeis
blindmeis

Reputation: 22445

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"

Upvotes: 0

Kishore Kumar
Kishore Kumar

Reputation: 21873

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>

Upvotes: 1

Akash Kava
Akash Kava

Reputation: 39956

DataTemplate should be inside ListBox.ItemTemplate.

Upvotes: 1

Related Questions