我有一个返回列表的类
class Book
{
public string Title { get; set; }
public string Author { get; set; }
public string Year { get; set; }
public static List<Book> GetList()
{
var bookList = new List<Book>();
bookList.Add(new Book
{
Author = "Robin Cook",
Title = "Vector",
Year = "1999"
});
bookList.Add(new Book
{
Author = "J.K. Rowling",
Title = "Harry Potter and Prisoner of Azkaban",
Year = "1999"
});
bookList.Add(new Book
{
Author = "George R.R. Martin",
Title = "A Dance with Dragons",
Year = "2011"
});
return bookList;
}
}
我希望该页面包含一个列表视图,每个单元格包含三元组作者 - 标题 - 年份,即
Robin Cook - Vector - 1999
...
在XAML代码中,我有
var listView = new ListView();
listView.ItemsSource = Book.GetList();
var cellTemplate = new DataTemplate(() =>
{
var textCell = new TextCell();
var titleLabel = new Label();
var authorLabel = new Label();
var yearLabel = new Label();
titleLabel.SetBinding(Label.TextProperty, "Title");
authorLabel.SetBinding(Label.TextProperty, "Author");
yearLabel.SetBinding(Label.TextProperty, "Year");
textCell.Text = titleLabel.Text + " - " + authorLabel.Text + " - " + yearLabel;
return textCell;
});
listView.ItemTemplate = cellTemplate;
Content = listView;
我看到的只是带有连字符的空单元格。你能告诉我我错过了什么吗?
答案 0 :(得分:0)
在模型中创建只读属性
public string DisplayText {
get {
return $"{Title} - {Author} - {Year}";
}
}
并绑定到它
var cellTemplate = new DataTemplate(() =>
{
var textCell = new TextCell();
textCell.SetBinding(TextCell.TextProperty, "DisplayText")
return textCell;
});
或者,您可以为要显示的每个值创建一个包含三个单独标签的ViewCell
var cellTemplate = new DataTemplate(() =>
{
var viewCell = new ViewCell();
var titleLabel = new Label();
var authorLabel = new Label();
var yearLabel = new Label();
titleLabel.SetBinding(Label.TextProperty, "Title");
authorLabel.SetBinding(Label.TextProperty, "Author");
yearLabel.SetBinding(Label.TextProperty, "Year");
StackLayout stack = new StackLayout();
stack.Children.Add(titleLabel);
stack.Children.Add(authorLabel);
stack.Children.Add(yearLabel);
viewCell.Content = stack;
return viewCell;
});
答案 1 :(得分:0)
在我看来,xaml组件和Book类之间应该存在一些绑定上下文。
如果您想以实施方式实施,可以执行以下操作:
var cellTemplate = new DataTemplate(()=>
{
var textCell = new TextCell();
if(i<Book.GetList().Count)
{
var titleLabel = new Label();
var authorLabel = new Label();
var yearLabel = new Label();
titleLabel.SetBinding(Label.TextProperty, "Title");
titleLabel.BindingContext = new { Title = Book.GetList()[i].Title };
authorLabel.SetBinding(Label.TextProperty, "Author");
authorLabel.BindingContext = new { Author = Book.GetList()[i].Author };
yearLabel.SetBinding(Label.TextProperty, "Year");
yearLabel.BindingContext = new { Year = Book.GetList()[i].Year };
textCell.Text = titleLabel.Text + " - " + authorLabel.Text + " - " + yearLabel;
i++;
}
return textCell;
}