Xamarin.Forms: 自定义列表视图单元格的数据绑定

Xamarin.Forms: Data Binding of custom listview cell

正在创建我的第一个根页面:

public class App : Application
{
    public App ()
    {
        MainPage = new NavigationPage (new ListExample ());
    }
}

这是我的员工对象:

public class Employee
{
    public string ImageUri { get; set; }
    public string DisplayName { get; set; }
    public string Twitter { get; set; }

    public Employee (string imageUri, string displayName, string twitter)
    {
        this.ImageUri = imageUri;
        this.DisplayName = displayName;
        this.Twitter = twitter;
    }
}

这就是我为 UITableView 设置项目的方式:

public class ListExample : ContentPage
{
    public ListExample ()
    {
        var listView = new ListView
        {
            RowHeight = 40
        };
        List<Employee> myListOfEmployeeObjects = new List<Employee> {
            new Employee("", "Max Mustermann", "@fake1"),
            new Employee("", "Eva Mustermann", "@fake2")
        };
        listView.ItemsSource = myListOfEmployeeObjects;
        listView.ItemTemplate = new DataTemplate(typeof(EmployeeCell));
    }
}

这是我的自定义 table 视图单元格:

public class EmployeeCell : ViewCell
{
    public EmployeeCell()
    {
        var image = new Image
        {
            HorizontalOptions = LayoutOptions.Start
        };
        image.SetBinding(Image.SourceProperty, new Binding("ImageUri"));
        image.WidthRequest = image.HeightRequest = 40;

        var nameLayout = CreateNameLayout();

        var viewLayout = new StackLayout()
        {
            Orientation = StackOrientation.Horizontal,
            Children = { image, nameLayout }
        };
        View = viewLayout;
    }

    static StackLayout CreateNameLayout()
    {

        var nameLabel = new Label
        {
            HorizontalOptions= LayoutOptions.FillAndExpand
        };
        nameLabel.SetBinding(Label.TextProperty, "DisplayName");

        var twitterLabel = new Label
        {
            HorizontalOptions = LayoutOptions.FillAndExpand
        };
        twitterLabel.SetBinding(Label.TextProperty, "Twitter");

        var nameLayout = new StackLayout()
        {
            HorizontalOptions = LayoutOptions.StartAndExpand,
            Orientation = StackOrientation.Vertical,
            Children = { nameLabel, twitterLabel }
        };
        return nameLayout;
    }
}

如果我理解正确,必须在自定义 table 视图单元格中设置绑定。系统采用我的对象的属性和 属性 的名称,绑定的名称必须匹配。

使用上面的代码会导致一个空视图。

我做错了什么?

我忘记设置 Content。要么使用

Content = listView;

或更详细:

Content = new StackLayout
{
    VerticalOptions = LayoutOptions.FillAndExpand,
    Children = { listView }
};