Search code examples
wpfdata-bindingmvvmicommandcommandparameter

How to get current element in WPF datagrid and how to do something with it?


Some time ago I began to study the MVVM pattern with this tutorial. I use MicroMvvm.

I have a WPF project with EntityFramework model. I wrote ViewModels and XAML views. I want to display my data in a DataGrid.(2 columns with data and 2 buttoncolumn: Edit, Delete)

<DataGrid Height="250" ItemsSource="{Binding Books}" AutoGenerateColumns="False" >
    <DataGrid.Resources>
        <DataTemplate x:Key="DeleteTemplate" >
            <Button x:Name="DeleteButton" Command="{Binding DeleteBook, Mode=OneWay}" CommandParameter="{Binding}" >Delete</Button>
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Title}"  Header="Book"/>
        <DataGridTextColumn Binding="{Binding Author}"  Header="Author"/>
        <DataGridTemplateColumn  CellTemplate="{StaticResource EditTemplate}" Header="Редактировать"/>
        <DataGridTemplateColumn  CellTemplate="{StaticResource DeleteTemplate}" Header="Удалить"/>
    </DataGrid.Columns>
</DataGrid>

In my LibraryViewModel.cs

#region Commands
void DeleteBookExecute()
{
    if (_books == null)
        return;

    //MessageBox.Show("This is delete button. Delete item id:" myMysticalObjectFromCommandParameter );
}
bool CanDeleteBookExecute()
{
    return true;
}
public ICommand DeleteBook
{
    get
    {
        return new RelayCommand(DeleteBookExecute, CanDeleteBookExecute);
    }
}

When I press the buttons (delete/edit) I want to to delete/edit the current object. I don't know how to do it in MVVM.

Can I do it with Command="{Binding DeleteBook, Mode=OneWay}" CommandParameter="{Binding}"?

If it's correct, how I can get the data from CommandParameter in my LibraryViewModel?


Solution

  • As DHN says, your command execution methods DeleteBookExecute(), CanDeleteBookExecute() should have a parameter of type object.

    You're ideas are pointing in the right direction. Try this:

    <DataGrid Name="LibraryGrid"
              Height="250" 
              ItemsSource="{Binding Books}" 
              AutoGenerateColumns="False" >
    

    and

    Command="{Binding DataContext.DeleteBook, ElementName=LibraryGrid}" CommandParameter="{Binding}"
    

    The use of ElementName with the DataContext.DeleteBook gets you the Command of the LibraryViewModel.