Bind command from Business object to View in MVVM

2019-01-27 06:17发布

问题:

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?

回答1:

First of all, do not place your command into your Model, instead use binding through RelativeSource. Like this:

<Button Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.RemoveCommand}" />

Second, you can bind your DataGrid SelectedItem to property of you ViewModel

<DataGrid SelectedItem="{Binding SelectedItemProperty, Mode=TwoWay}" .../>

or pass your selected item through CommandParameter.

<Button Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.RemoveCommand}" CommandParameter="{Binding}" />