I populate DataGrid in WPF through MVVM. I have business object with 4 properties to create the Row and Columns in the DataGrid.
<DataGrid CanUserAddRows="True" ItemsSource="{Binding Path=PersonsInfo}" AutoGenerateColumns="False"
CanUserDeleteRows="True" CanUserReorderColumns="True"
CanUserSortColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"/>
<DataGridTextColumn Header="Age" Binding="{Binding Path=Age}"/>
<DataGridTextColumn Header="Date Of Birth" Binding="{Binding Path=DateOfBirth}"/>
<DataGridTextColumn Header="Address" Binding="{Binding Path=Address}"/>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Button Content="Remove..." Margin="3" Command="{Binding Path=RemoveCommand}" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
In the above code when I click the button, I need to remove the records from the DataGrid.
So I need the requirement that, I should be having the Command in the business object class instead of having inside the ViewModel class.
While I am clicking the button in each row, that corresponding row should be deleted.
Hence how can I find which item is selected in the DataGrid to delete the row through command execution in business object class because business object class does not have information about items of the DataGrid?
First of all, do not place your command into your
Model
, instead use binding throughRelativeSource
. Like this:Second, you can bind your
DataGrid
SelectedItem
to property of youViewModel
or pass your selected item through
CommandParameter
.