【问题标题】:Xamarin Forms: access View of databound ListView item?Xamarin Forms:访问数据绑定 ListView 项目的视图?
【发布时间】:2017-01-04 11:12:42
【问题描述】:

我的ListView 有一个自定义数据模板。 业务对象(例如“Person”的类型)有很多属性,我想避免每个属性都有太多的绑定,因为有些很难设置。

所以我更愿意设置视图的属性值(例如“PersonCell”)手动/直接,就在 View 创建之后它的BindingContext/DataContext 已设置为“Person”实例。

问题:我不知道如何访问那些View 实例。

是否可以访问为数据项创建的View? 我会在哪里做这个? (在OnBindingContextChanged 中,我似乎无法访问与提供的数据项/BindingContext 关联的视图)

【问题讨论】:

    标签: listview xamarin.forms


    【解决方案1】:

    如果您将DataTemplate 提取到一个控件中,这样您就有:

    partial class PersonCell : Grid
    {
       public PersonCell()
       {
          InitialiseComponent();
       }
    
       Protected Override OnBindingContextChanged()
       {
          //set up bindings here
       }
    }
    

    在 Xaml 中定义您的视图

    然后在你的ListView 中像这样使用它:

    <ListView>
      <ListView.ItemTemplate>
         <DataTemplate>
           <custom:PersonCell/>
         </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
    

    custom 是您定义的 Xaml 命名空间(PersonCell 所在的位置)

    【讨论】:

    • 我终于通过将 PersonCell 实例存储在 OnBindingContextChanged 中的 Person 对象中解决了这个问题,这样我以后就可以在页面的任何位置访问它。不好的风格,但它的工作原理。
    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多