Bind command from Business object to View in MVVM

夙愿已清 提交于 2019-11-28 06:21:40

问题


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}" />


来源:https://stackoverflow.com/questions/10596094/bind-command-from-business-object-to-view-in-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!