2

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

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

1 回答 1

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; }
}
于 2013-02-15T18:14:16.053 回答