XAML ListBox仅显示类名称 [英] XAML ListBox only shows class name

查看:233
本文介绍了XAML ListBox仅显示类名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使我的班级属性显示在列表框中?

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

推荐答案

当前的实现存在一些问题.首先,应将DataTemplate放置在ListBox的ItemTemplate内.其次,每个ListBoxItem的DataContext将是Player的实例,因此您应直接绑定到FirstNameLastName.第三,应该公开Player中的属性,以便DataBinding起作用.

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

此外,无需将收集项逐项添加到ListBox,只需将其设置为ItemsSource

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

lstPlayers.ItemsSource = Players;

这篇关于XAML ListBox仅显示类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆