创建我的第一个根页面:
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));
}
}
这是我的自定义表格 View 单元格:
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;
}
}
如果我理解正确,必须在自定义表格 View 单元格中设置绑定(bind)。系统采用我的对象的属性,属性名称和绑定(bind)名称必须匹配。
使用上面的代码会导致一个空 View 。
我做错了什么?
最佳答案
我忘记设置内容
。要么使用
Content = listView;
或更详细:
Content = new StackLayout
{
VerticalOptions = LayoutOptions.FillAndExpand,
Children = { listView }
};
关于c# - Xamarin.Forms:自定义 ListView 单元格的数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28720069/