Reputation: 10983
I have a ListView
binded to an ObservableCollection<User>
, and a button Delete
.
I want to delete the selected item from the ListView
when I hit the Delete
button, but I coudn't find a way to pass the selected item to the Button's CommandParameter
.
<Button Content="Delete" Command="{Binding DeleteCommand}" CommandParameter="{Binding ?}" />
<ListView ItemsSource="{Binding Path=UserList}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemeberBinding="{Binding Name}" />
<GridViewColumn DisplayMemeberBinding="{Binding Age}" />
</GridView>
</ListView.View>
</ListView>
How could you do that ?
Upvotes: 1
Views: 1805
Reputation: 44028
You could use an ElementName
Binding:
<Button Content="Delete" Command="{Binding DeleteCommand}"
CommandParameter="{Binding SelectedItem, ElementName=MyListView}" />
<ListView ItemsSource="{Binding Path=UserList}" x:Name="MyListView">
Edit:
If you don't want to use x:Name
(for whatever reasons) you can create a SelectedItem
property in your ViewModel and bind the ListView.SelectedItem
property to that. That way you don't need a CommandParameter
at all because you already have that information at the ViewModel level:
public class MyViewModel
{
public MyData SelectedItem {get;set;} //NotifyPropertyChanged(), etc.
public DelegateCommand DeleteCommand {get;set;}
void OnDelete()
{
//Here you delete SelectedItem, no need for CommandParameter
}
}
XAML:
<Button Content="Delete" Command="{Binding DeleteCommand}"/>
<ListView ItemsSource="{Binding Path=UserList}"
SelectedItem="{Binding SelectedItem}">
Side Comment: x:Name
is perfectly fine.
Upvotes: 2