【问题标题】:Bind command from Business object to View in MVVM将业务对象的命令绑定到 MVVM 中的视图
【发布时间】:2012-05-22 16:34:47
【问题描述】:

我通过 MVVM 在 WPF 中填充 DataGrid。我有具有 4 个属性的业务对象来在 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>

在上面的代码中,当我单击按钮时,我需要从 DataGrid 中删除记录。

所以我需要这样的要求,即我应该在业务对象类中包含命令,而不是在 ViewModel 类中。

当我单击每一行中的按钮时,应该删除相应的行。

因此,由于业务对象类没有关于DataGrid项目的信息,如何通过业务对象类中的命令执行找到DataGrid中选择了哪个项目来删除行?

【问题讨论】:

    标签: wpf mvvm datagrid business-objects


    【解决方案1】:

    首先,不要将您的命令放入您的Model,而是通过RelativeSource 使用绑定。像这样:

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

    其次,您可以将您的DataGrid SelectedItem 绑定到您的财产ViewModel

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

    或通过CommandParameter传递您选择的项目。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-29
      • 2013-01-16
      • 2014-06-27
      • 2011-04-04
      • 1970-01-01
      • 2010-11-28
      • 2020-03-10
      相关资源
      最近更新 更多