【问题标题】:Xamarin Forms binding to a custom cell without hardcoded property namesXamarin Forms 绑定到没有硬编码属性名称的自定义单元格
【发布时间】:2017-09-09 18:00:45
【问题描述】:

我有一个绑定到自定义单元格的工作列表视图。但是,我想知道我是否真的必须拥有一个具有与自定义单元格属性一样命名的属性的模型。

我的自定义视单元(很多东西都遗漏了):

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 的属性的对象列表。我想将此自定义单元格与任何类型的对象列表一起重用,并像我的评论显示的那样在页面上指定绑定,但这没有用。

我在这里期待错误的事情还是我的方法错误?

【问题讨论】:

  • 您是否希望同一页面的标题保持不变?还是您希望标题的内容根据项目的内容而动态变化?
  • 同一页面的常量,但许多页面都希望使用相同的自定义单元格,因此我不希望该单元格需要命名模型属性

标签: xamarin data-binding xamarin.forms


【解决方案1】:

为标签设置绑定的方式是 bindingcontext 中的“Header”,在 GetTopics() 中没有名为“Header”的属性,因此您已将标签的绑定源设置为 RecordCell。

headingLbl.SetBinding(Label.TextProperty,
                    new Binding("Heading",BindingMode.Default, null, null, null, source: this));

现在

cell.SetBinding (RecordListCell.HeadingProperty, "Name");

此代码应该可以工作,希望对您有所帮助!

【讨论】:

  • 反正那些附加参数都是默认的吧?
  • 是的,你说得对,这些是最后一个参数默认的,即 Source:null 是默认值,而不是我分配的父 RecordListCell 使其查找 Heading 属性。跨度>
【解决方案2】:

ListView 项目的 BindingContext 绑定到项目的模型。您必须想办法将该数据插入到视图单元格和数据模板中。

您可以更改自定义视图单元格构造函数以接受(每页)标题值

MyCustomCell(string perPageHeadingText)

并将其指定为标题值(因为它将在每个页面上都是唯一的),其余的视单元内容可以像往常一样绑定到项目源。

然后您将使用不同的 DataTemplate 构造函数来创建模板:

var myTemplate = new DataTemplate(() => { return new MyCustomCell("MyPageTitle"); });

【讨论】:

  • 我的错。我的意思是每个页面的属性名称是唯一的,而不是值。无论如何,Dinesh 回答为我解决了这个问题。还是谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 2018-09-09
  • 2016-12-30
  • 2015-10-25
  • 1970-01-01
相关资源
最近更新 更多