简体   繁体   中英

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应该在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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM