Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 89864

Xamarin.Forms parent BindingContext in DataTemplate in the XAML

$
0
0

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"/>
<DataTemplate>
    <cells:CartViewCell ParentContext="{Binding BindingContext, Source={x:Reference cart}}"/>
</DataTemplate>

In the class of my custom viewcell:

public partial class CartViewCell : ViewCell
    {
        public CartViewCell()
        {
            InitializeComponent();
        }

        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 .}"/>
</Image.GestureRecognizers>

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.


Viewing all articles
Browse latest Browse all 89864

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>