Windows Phone列表未显示数据

时间:2013-02-15 18:03:54

标签: c# .net windows-phone-7 xaml windows-phone-7.1

我有以下代码用于测试,如何输入到列表中。这些项目存在于列表中,但未显示。

public MyFellows()
    {
        InitializeComponent();
        List<Fellow> fellowList = new List<Fellow>();
        for (int i = 0; i < 2; i++)
        {
            Fellow fellow = new Fellow();
            fellow.Name = "Danish " + i;
            fellow.Email = "Email " + i;
            fellowList.Add(fellow);
        }
        lbFellows.ItemsSource = null;
        lbFellows.ItemsSource = fellowList;
    }

    private class Fellow
    {
        public string Name { get; set; }
        public string Email { get; set; }
    }

正在使用xaml

<ListBox x:Name="lbFellows" Margin="8,8,8,177">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical" Width="Auto" Height="300">
                        <TextBlock x:Name="tbName" Width="Auto" FontSize="22" FontWeight="Bold" Text="{Binding Name}" />
                        <TextBlock x:Name="tbEmail" Width="Auto" FontSize="22" Height="Auto" Text="{Binding Email}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

1 个答案:

答案 0 :(得分:1)

首先,WPF仅绑定到属性,属性必须存在于对象的DataContext中。

你必须改变这样的代码:

public List<Fellow> fellowList { get; set; }
// Constructor
public MainPage()
{
    InitializeComponent();

    fellowList = new List<Fellow>();
    for (int i = 0; i < 2; i++)
    {
        Fellow fellow = new Fellow();
        fellow.Name = "Danish " + i;
        fellow.Email = "Email " + i;
        fellowList.Add(fellow);
    }
    this.DataContext = this;
    //lbFellows.ItemsSource = null;
    lbFellows.ItemsSource = fellowList;
}

public class Fellow
{
    public string Name { get; set; }
    public string Email { get; set; }
}