I have a datagrid that displays all of the records that exist in an SQL database table and I would like to add a single button to my UI that allows users to delete the record(s) he or she has selected. Most of the references I have found for this revolve around adding a delete button to each row or involve code behind. I am using an MVVM pattern and I do not want a button in each row. Currently I am able to delete one record at a time but need assistance with how to iterate through the selected items. My code is as follows:
XAML
<Button x:Name="revokeBtn"
Grid.Row="0"
Grid.Column="4"
ToolTip="Revoke Selected License or Licenses"
Content="Revoke"
Command="{Binding RevokeSelectedCommand}"
CommandParameter="{Binding}">
</Button>
<DataGrid x:Name="licenseGrid"
ItemsSource="{Binding LoggedUsers}"
SelectedItem="{Binding SelectedLicenses}"
Style="{DynamicResource DataGridStyle}"
Grid.Row="2"
Grid.Column="1"
Grid.ColumnSpan="6"
Height="535"
VerticalAlignment="Top"
IsReadOnly="True"
AutoGenerateColumns="False"
HeadersVisibility="Column"
SelectionMode="Extended"
CanUserDeleteRows="True"
EnableRowVirtualization="False">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</DataGrid.RowStyle>
With DataGrid.Columns that are bound to the table columns.
ViewModel
public ObservableCollection<MD_LoggedUsersModel> LoggedUsers
{
get { return _loggedUsers; }
set { _loggedUsers = value; NotifyPropertyChanged(nameof(LoggedUsers)); }
}
public MD_LoggedUsersModel SelectedLicenses
{
get
{
return _selectedLicenses;
}
set
{
if (_selectedLicenses != value)
{
_selectedLicenses = value;
OnPropertyChanged(nameof(SelectedLicenses));
}
if (_selectedLicenses == null)
{
LoadData();
}
}
}
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
if (_isSelected == value) return;
_isSelected = value;
OnPropertyChanged(nameof(IsSelected));
}
}
public ICommand RevokeSelectedCommand
{
get
{
return _revokeSelectedCommand ?? (_revokeSelectedCommand = new CommandHandler(() => RevokeSelected(), _canExecute));
}
}
private void RevokeSelected()
{need to iterate through selected rows here}
What is the best way to accomplish this?