【问题标题】:How to get Binding-Context on creating DataTemplate如何在创建 DataTemplate 时获取 Binding-Context
【发布时间】:2021-08-05 06:03:08
【问题描述】:

有没有办法在枚举模板中获取 Binding-Context 本身?

this.CollectionView.ItemTemplate = new DataTemplate(() =>
{
    var view = new SubView();
    view.SetBinding(SubView.SourceProperty, new Binding()
    {
        Source = ??? // <- here
    });
    
    return view;
};

注意:
Path = "." 在 Android 上运行良好。但在 iOS 上,源是重复的。
我已经检查了 CollectionView.ItemsSource 中没有重复项。

【问题讨论】:

  • 根据你的代码,我不清楚你遇到了什么问题吗?如果想通过后面的代码使用collectionview绑定,可以看一下:xamarin.forms collectionview
  • 谢谢回复,Cherry Bu。 DataTemplate 构造函数的参数中的 Action 被执行的次数与元素的数量一样多。所以我想象会有一种方法可以将元素本身作为参数传递给 Action。
  • 你为什么要这样做?对于collectionview.ItemTemplate,我一般用this document,不知道要不要用relative binding

标签: xamarin.forms binding collectionview itemssource


【解决方案1】:

我是这个平台的新手,希望能帮上忙。 我了解您想要获取列表中每个元素的 BindingContext。如果我的解释正确,那么您可以这样做:

public partial class NotificationsPage : ContentPageBase
{
    public NotificationsPage()
    {
        InitializeComponent();
        CollectionView.ItemTemplate = new DataTemplate(() =>
        {
            return new Item();
        });
    }
}

public class Item : ContentView
{
    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();
        if (BindingContext is ItemModel item)
        {
            var name = item.Name;
        }
    }
}

public class ItemModel
{
    public string Name { get; set; }
}

DataTemplate 不包含可访问的 BindingContext,BindingContext 被传递给包含 DataTemplate 的元素。

【讨论】:

  • 感谢 AlexDev 的回复。我明白这是不可能的。
猜你喜欢
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2012-06-10
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
相关资源
最近更新 更多