MVVM Light DataGrid DeleteCommand

时间:2013-01-26 22:31:13

标签: c# wpf mvvm wpfdatagrid mvvm-light

我项目的简短结构是(使用MVVM Light Toolkit):

  • 使用DataGrid查看(UserControl)

  • 视图模型

  • DataObjects with ValueObjects

  • DB

我正在使用一个ObservableCollection进行数据绑定到我的DataGrid, 但我坚持在Datagrid中删除一行并将其保存到DataBase。

在较旧的项目中,我使用了System.Windows.Input中的CommandManager.PreviewExecuted事件,并在那里检查了DataGrid.DeleteCommand的事件参数。只需这样:

if(e.Command == DataGrid.DeleteCommand)
{
    DataAccessContext.Sample.DeleteOnSubmit(data);
    DataAccessContext.SubmitChanges();
}

我现在用Google搜索了几个小时,但没有找到正确的方法。 我尝试使用PassEventArgsToCommand,但Event DataGrid.DeleteCommand或CommandManager.PreviewExecuted未触发,SelectionChangedCommand工作正常,但我不知道如何检查重要的DataGrid.DeleteCommand。

这是我的xaml:

<DataGrid x:Name="dataGrid1" ItemsSource="{Binding Items}" CanUserAddRows="True" CanUserDeleteRows="True" AutoGenerateColumns="False" Height="391" HorizontalAlignment="Left" VerticalAlignment="Top" Width="auto" Margin="2,0,0,0" RowEditEnding="dataGrid1_RowEditEnding" CellEditEnding="dataGrid1_CellEditEnding">
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="SelectionChanged">
                                <cmd:EventToCommand
                                Command="{Binding SelectionChangedCommand,Mode=OneWay}"
                                CommandParameter="{Binding SelectedItems,ElementName=dataGrid1}">
                                </cmd:EventToCommand>
                            </i:EventTrigger>
                            <i:EventTrigger EventName="DataGrid.DeleteCommand"> //I've also tried PreviewExecuted and CommandManager.PreviewExecuted as EventName
                                <cmd:EventToCommand
                                    Command="{Binding SelectedItems,Mode=OneWay}"
                                    CommandParameter="{Binding ExecutedRoutedEventArgs, ElementName=dataGrid1}"
                                    PassEventArgsToCommand="True"
                                    ></cmd:EventToCommand>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                            <DataGrid.Columns>
                            <DataGridTextColumn Header="Name" Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Width="auto"></DataGridTextColumn>
                        <DataGridTextColumn Header="Vorname" Binding="{Binding Surname, UpdateSourceTrigger=PropertyChanged}" Width="auto"></DataGridTextColumn>
            </DataGrid.Columns>
                    </DataGrid>

感谢您的回答和最好的问候

1 个答案:

答案 0 :(得分:0)

尝试禁用DataGrid上的删除,而是将Delete键挂钩到命令(通过KeyBinding),该命令将执行保存并从源集合中删除该行。

看看这个question