0
votes

I am using Xamarin.Forms, and I'm looking for a way to have a databound ListView with custom cells, and in those custom cells, there is a Delete button that is bound to a Command in my ViewModel.

Here is my code...

<ListView ItemsSource="{Binding SelectedServiceTypes}" IsVisible="{Binding ShowSelectedServiceTypes}" HeightRequest="110" RowHeight="30">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.View>
                    <StackLayout Orientation="Horizontal" HeightRequest="30">
                        <Label Text="{Binding ServiceCode}" HeightRequest="30" />
                        <Label Text="-" HeightRequest="30" />
                        <Label Text="{Binding ServiceDescription}" HeightRequest="30" />
                        <Button 
                            Text="Delete"
                            HeightRequest="30" 
                            HorizontalOptions="End" 
                            VerticalOptions="Start" 
                            Command="{Binding DeleteServiceTypeCommand}"
                            CommandParameter="{Binding ID}" />
                    </StackLayout>
                </ViewCell.View>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

The ListView is bound to an ObservableCollection. I want the delete button to use a Command and pass a CommandParameter to my View Model.

    private Command _deleteServiceTypeCommand;
    public Command DeleteServiceTypeCommand
    {
        get 
        {
            if (_deleteServiceTypeCommand == null)
                _deleteServiceTypeCommand = new Command<string> ((serviceTypeID) => RemoveServiceType (serviceTypeID) );

            return _deleteServiceTypeCommand;
        }
    }

I wasn't sure if this is possible in Xamarin.Forms. It's almost like the cell needs to have two BindingContext, one being the element in the collection(to get the ID value) and the other being the View Model(to have the Command work).

Any ideas?

1
You could make the list elements aware of their parent collection, and put the Delete... command there. No parameter needed then. Just a matter if this.Parent.Remove(this). Otherwise, you'll have to use RelativeSource binding to get back up to the model.glenebob

1 Answers

0
votes

So after more research, I was able to find the nuget package Xamarin.Forms.Behaviors which adds something similar to RelativeSource binding.

https://github.com/corradocavalli/Xamarin.Forms.Behaviors

It's implementation example can be found here.

http://codeworks.it/blog/?p=216