从datagrid wpf中获取所选记录?

时间:2011-04-12 10:41:41

标签: c# wpf datagrid indexing

我的照片中有表格。根据post field复选框,如果选中它,我会写入一个文件并从我的数据库中删除这些记录。如果它未检查的记录将保留在我的数据库中。问题是当我然后尝试访问那些记录时我得到一个异常(无法找到onject)因为我试图访问datagrid.SelectedIndex它给我datagrid索引而不是记录指数。有没有办法获得记录索引?我将自动索引增加1作为每条记录的唯一ID。

enter image description here

先谢谢

1 个答案:

答案 0 :(得分:0)

如果您使用viewmodel或其他东西,您可以简单地使用命令和选定的datagridrow作为命令参数。在您的命令中,您可以轻松访问您的下划线数据,并检查您的“发布”属性和您的文件,并删除您的收藏中的行。

<Buttons Command="{Binding WriteCommand}" CommandParameter="{Binding ElementName=MyDataGridCtrl, Path=SelectedItem}" />

如果您有一个DataTable作为数据源,您的Command可能如下所示

 private DelegateCommand<DataRowView> _writeCommand ;
 public ICommand WriteCommand
    {
        get
        {
            return this._writeCommand ??
                   (this._writeCommand = new DelegateCommand<DataRowView>(this.WriteCommandExecute, this.CanWriteCommandExecute));
        }
    }

 private bool CanEditDataCommandExecute(DataRowView rowToWrite)
    {
        return rowToWrite!= null && (bool)rowToWrite["Post"];//if post is a bool
    }

  private void EditDataCommandExecute(DataRowView rowToWrite)
    {
        if (!this.CanEditDataCommandExecute(rowToWrite))
            return;

        //do your stuff here
    }
相关问题