Question

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?

Was it helpful?

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.

OTHER TIPS

I'm a bit curious that your command methods have no parameters. I would expect them to look like this

void DoSomething(object param) {}
bool CanDoSomething(object param) {}

Nevertheless, I would bind the SelectedItem property of the DataGrid to a property on the VM. For some more information, pls have a look here.

<DataGrid ItemsSource={Binding Books} SelectedItem={Binding SelectedBook} />

So you can easily access the 'current' item in your commands.

Hope this helps a bit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top