How to get Binding-Context on creating DataTemplate

616 Views Asked by At

Is there a way to get the Binding-Context itself in an enumerated template?

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

Note:
Path = "." works fine on Android. but on iOS, the source is duplicated.
I have already checked that there are no duplicates in CollectionView.ItemsSource.

1

There are 1 best solutions below

1
AlexDev On

I'm new to the platform I hope I can help. I understand that you want to get the BindingContext of each element in the list. If I am interpreting correctly, then this is what you can do:

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 does not contain an accessible BindingContext, the BindingContext is passed to the element containing the DataTemplate.