Xamarin.Forms parent BindingContext in DataTemplate in the XAML

ThomasClopThomasClop USMember ✭✭
edited March 2018 in Xamarin.Forms

After few hours of research, I finally found a solution to my problem. I saw that other people had the same problem : I have a listview with a custom viewcell as datatemplate, the contentpage viewmodel has a shared command "RemoveItem" and I want to invoke it from my custom viewcell.
The original error was : "Xamarin.Forms.Xaml.XamlParseException: No Property of name ElementName found".

In the XAML of my contentpage ("cells" reference the namespace with my customs viewcells):

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Name="cart"/>
    <cells:CartViewCell ParentContext="{Binding BindingContext, Source={x:Reference cart}}"/>

In the class of my custom viewcell:

public partial class CartViewCell : ViewCell
        public CartViewCell()

        public static readonly BindableProperty ParentContextProperty =
            BindableProperty.Create("ParentContext", typeof(object), typeof(CartViewCell), null, propertyChanged: OnParentContextPropertyChanged);

        public object ParentContext
            get { return GetValue(ParentContextProperty); }
            set { SetValue(ParentContextProperty, value); }

        private static void OnParentContextPropertyChanged(BindableObject bindable, object oldValue, object newValue)
            if (newValue != oldValue && newValue != null)
                (bindable as CartViewCell).ParentContext = newValue;

And in the XAML of my customviewcell:

<ViewCell xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Name="cartCell"><Image.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding ParentContext.RemoveItem, Source={x:Reference cartCell}}" CommandParameter="{Binding .}"/>

Sorry if I made some mistakes, french guy :blush:
If you have a better solution I am interested because it's look like a hack for me.


  • MulflarMulflar ESUniversity ✭✭

    OMG!! THANKS ;-)

  • Samuel.4254Samuel.4254 USMember

    Thanks so much ! I was stuck 2 days on this !

  • SzeYuanNgSzeYuanNg MYMember

    Thank you so much. your solution is work.
    finally I can go sleep.

  • NMackayNMackay GBInsider, University mod


    Love posts like this, it will save people hours of head banging.

  • TomtomFooBarTomtomFooBar GTMember ✭✭
    edited June 2018

    Nice solution! But I was wondering, isn't the assignment in your OnParentContextPropertyChanged redundant?
    I mean, the propertyChanged handler of your BindableProperty is invoked after the property is assigned the new value, so why assign it again in the handler?

Sign In or Register to comment.