1 min read

Binding CollectionViewItem to a Parent (CollectionView) Property

I ran into a problem nesting a Xamarin.Forms button in a CollectionView. Each of the items was to contain an "edit" button that would open another page to allow editing.

The binding I originally tried was:

<Button Text="Edit" Command="{Binding Path=EditTagCommand}" CommandParameter="{Binding}" />

Of course that failed because of the BindingContext in CollectionView.ItemTemplate (the currently bound item). "Failed" in this case meant nothing happened since there was no "EditTagCommand" property defined on the item view model.

I was going to bind onto the parent CollectionView's BindingContext like this:

Command="{Binding Source={RelativeSource AncestorType={x:Type CollectionView}, Path=BindingContext.EditTagCommand}"

I had used that technique before, but then I encountered this:

 <Button Text="Edit" Command="{Binding Source={RelativeSource AncestorType={x:Type vm:LoginViewModel}}, Path=EditTagCommand}" CommandParameter="{Binding}" />
                                

Using AncestorType with my ViewModel type, it allows binding directly to the property.

While this is documented on MSDN, I originally found this on: https://devblogs.microsoft.com/xamarin/binding-possibilities-relativesource/

MSDN reference: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/relative-bindings#bind-to-an-ancestor