Reputation: 61
I have an issue on my ListView in my xamarin.forms application where I use MVVM pattern. I hope you could help me. Here is my xaml:
<ListView x:Name="MissingVolumeListView"
ItemsSource="{Binding Volumes}"
SelectedItem ="{Binding Id}"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid x:Name="Item">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="40"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding Name}" Style="{StaticResource UsualLabelTemplate}"/>
<Button Grid.Column="1" x:Name="DeleteButton" Text ="-" BindingContext="{Binding Source={x:Reference MissingVolumeListView}, Path=BindingContext}" Command="{Binding DeleteVolumeCommand}" CommandParameter="{Binding Source={x:Reference Item}, Path=BindingContext}"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Then I get the DeleteVolumeCommand in my ViewModel:
private ICommand _deleteVolumeCommand;
public ICommand DeleteVolumeCommand
{
get
{
{
if (_deleteVolumeCommand == null)
{
_deleteVolumeCommand = new Command((e) =>
{
var item = (e as Volume);
int index = MissingVolumeListView.Items.IndexOf(item);
});
}
return _deleteVolumeCommand;
}
}
}
As you can see, what I want is to get selected item when I click a Button in my ListView. Then, I want to get my ListView to get index of the selected item to delete it from my ListView
Thank you for your help
Upvotes: 1
Views: 5705
Reputation: 6953
First of all change your delete button XAML.
<Button Grid.Column="1"
Text ="-"
Command="{Binding Path=BindingContext.DeleteVolumeCommand, Source={x:Reference MissingVolumeListView}}"
CommandParameter="{Binding .}" />
The command needs to have its binding context changed to the view model via the listview name.
The command parameter however can just pass the current binding which is the list view item.
In your view model you cannot reference any controls via name. Instead use the list that the list view has its ItemsSource bound to - Volumes.
You can remove the item directly.
_deleteVolumeCommand = new Command((e) =>
{
var item = (e as Volume);
Volumes.Remove(item);
});
Remember to also call notify property changed if Volumes is not an ObservableCollection.
Upvotes: 15