Xaml Code What other property for Datagrid Button Should be used to trigger the CmdDeleteUser ICommand Property. The Datagrid Row gets Selected but then the Delete button Doesn't work. '''
<DataGridTemplateColumn Header="Delete Record" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<Button Width="60" Margin="2" Command="{Binding CmdDeleteUser}" Content="Delete" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
'''
ViewModel Code '''
public ICommand CmdDeleteUser
{
get
{
return new DelegateCommand(DeleteUser);
}
}
private void DeleteUser()
{
if (null != SelectedCustomer)
{
customer.Remove(SelectedCustomer);
}
try
{
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand($"Delete from Customer where Id='{Convert.ToInt32(SelectedCustomer.id)}'", con);
cmd.ExecuteNonQuery();
Customer current = customer.Where(x => x.id == SelectedCustomer.id).FirstOrDefault();
customer.Remove(current);
}
catch (Exception)
{
}
finally
{
con.Close();
}
}
'''
Inside your Listview you can use the RelativeSource to access the Command in the ViewModel:
Command="{Binding DataContext.CmdDeleteUser, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding}
The AncestorType ist the type of your control, which have the Bindingcontext you need.
The problem is that you try to Bind the CmdDeleteUser in your DataGrid meanwhile the Command is defined in your ViewModel but the BindingContext of your DataGrid is not the ViewModel, if you use an ItemsSource.