我有一个绑定到自定义单元格的工作列表视图。但是,我想知道我是否真的必须有一个模型,其属性命名就像自定义单元格属性一样。
我的自定义视图单元格(省略了很多东西(:
public class RecordListCell : ViewCell
{
public static readonly BindableProperty HeadingProperty = BindableProperty.Create ("Heading", typeof (string), typeof (RecordListCell), null);
public string Heading {
get { return (string)GetValue (HeadingProperty); }
set { SetValue (HeadingProperty, value); }
}
protected Label headingLbl { get; set; }
public RecordListCell ()
{
headingLbl = new Label () ;
headingLbl.SetBinding (Label.TextProperty, new Binding ("Heading"));
// from here on I construct a stacklayout and insert the label above
}
}
我的页面(遗漏了很多东西(
public TopicsPage ()
{
_topicList = new ListView ();
var cell = new DataTemplate (typeof (RecordListCell));
// NOT WORKING
// cell.SetBinding (RecordListCell.HeadingProperty, "Name");
// working (I must name the property exactly like the property in my custom cell)
cell.SetBinding (RecordListCell.HeadingProperty, "Heading");
_topicList.ItemTemplate = cell;
_topicList.ItemsSource = MyRepo.GetTopics();
}
所以上面有效,但我被迫让 MyRepo.GetTopics(( 返回具有名为 Heading 的属性的对象列表。我想在任何类型的对象列表中重复使用此自定义单元格,并且只是像我的评论所示在页面上指定绑定,但这并不费力。
我在这里期待错误的事情还是我的方法错误?
为标签设置绑定的方式是 bindingcontext 中的"Header",其中 GetTopics(( 中没有名为"Header"的属性,因此您已将标签的绑定源设置为 RecordCell。
headingLbl.SetBinding(Label.TextProperty,
new Binding("Heading",BindingMode.Default, null, null, null, source: this));
现在
cell.SetBinding (RecordListCell.HeadingProperty, "Name");
这段代码应该可以工作,希望有帮助!
ListView 项的 BindingContext 与项的模型相关联。您必须找到另一种方法将该数据插入视图单元格和数据模板。
您可以更改自定义视图单元格构造函数以接受(每页(标题值
MyCustomCell(string perPageHeadingText)
并将其指定为标题值(因为它每页都是唯一的(,其余的 viewcell 内容可以像往常一样绑定到项目源。
然后,您将使用不同的数据模板构造函数来创建模板:
var myTemplate = new DataTemplate(() => { return new MyCustomCell("MyPageTitle"); });