I have a WPF application with a DataGrid
, menus and buttons. When rows in the DataGrid
are selected, buttons and menu items are activated, to enable deleting data from a database.
Partial XAML for this main window:
<Button ToolTip="Delete Record" Command="{Binding DeleteCommand}" Name="button_delete" IsEnabled="False"/>
<MenuItem>
<MenuItem Header="Delete" IsEnabled="False" Name="menuItem_delete" Command="{Binding DeleteCommand}"/>
</MenuItem>
<DataGrid Name="BooksDataGrid" ItemsSource="{Binding BooksList}" SelectionChanged="dataGrid_selectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Header="Title" Binding="{Binding title_long}"/>
<DataGridTextColumn Header="ISBN" Binding="{Binding isbn}"/>
</DataGrid.Columns>
</DataGrid>
The DeleteCommand is to be defined within the class that is the DataContext
for the main window above. Partial code for this class is as follows:
sealed class BookViewModel
{
public ObservableCollection<IBook> Books { get; private set; }
// load data command code
// delete record command code
// ...
public void deleteAction(IEnumerable<string> isbnList)
{
// delete data from database
// this already works
}
}
There is already a command implemented to load data from the database. That was implemented in a very similar fashion to the answer to the following question: How to bind WPF button to a command in ViewModelBase?
What is to be achieved:
- When items in the
DataGrid
are selected, the UI elements for the delete command are activated if one or more items are selected. This is already achieved with the following event handler, in the codebehind for the main window:
private void dataGrid_selectionChanged(object sender, SelectionChangedEventArgs args)
{
// this works
// if nothing is selected, disable delete button and menu item
if (BooksDataGrid.SelectedItems.Count == 0)
{
button_deleteBook.IsEnabled = false;
menuItem_deleteBook.IsEnabled = false;
}
else
{
// delete command can now be executed, as shown in the binding in XAML
button_deleteBook.IsEnabled = true;
menuItem_deleteBook.IsEnabled = true;
}
}
- The delete command to be implemented. What is not clear so far, is how to pass parameters to a command implemented in the ViewModel (
DataContext
for the View). I am new to WPF and trying to understand how commands work. Specifically, this command should take a parameter ofIEnumerable<string>
, or perhaps a collection ofstring
. I have already completed and tested thedeleteAction
method. Thestring
objects are to be the values in the "ISBN" column of the selected rows of theDataGrid
.