I am trying to bind a command (with RelativeSourceExtension) to a button within a StackLayout using BindableLayout.ItemsSource in an Xamarin.Forms App.
Not working version of MyControl.xaml:
<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
...
x:Class="MyApp.Views.MyControl">
<StackLayout Orientation="Horizontal"
BindableLayout.ItemsSource="{Binding Data}">
<Button Command="{Binding Source={RelativeSource AncestorType={x:Type views:MyControl}}, Path=BindingContext.RemoveCommand}"
CommandParameter="{Binding}"
Text="Remove"/>
</StackLayout>
</Grid>
Unfortunately the button is "inactive" and does not let you "click". The same command binding works fine in a ListView with ItemsSource.
Working version of MyControl.xaml:
<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
...
x:Class="MyApp.Views.MyControl">
<ListView ItemsSource="{Binding Data}"
HasUnevenRows="true">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Button Command="{Binding Source={RelativeSource AncestorType={x:Type views:MyControl}}, Path=BindingContext.RemoveCommand}"
CommandParameter="{Binding}"
Text="Remove"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Control Usage in MainPage.xmal:
<Grid BindingContext="{Binding Cart}">
...
<views:MyControl/>
....
</Grid>
Am I generally doing something wrong? Or is there a trick to make this work?
You missed using StackLayout.ItemTemplate and after DataTemplate in you xaml. Your button is not wrapped in a good way. That's it.