如何在WPF中获取Datagrid的单元格数据值?

时间:2016-04-07 06:49:15

标签: wpf xaml wpf-controls wpfdatagrid datagridcell

我对WPF非常陌生,我希望使用Datagrid控件创建数据输入表单。我坚持,如何获取单元格数据值将它们存储到数据库中?

就像在Windows中一样,我们过去常常通过gridview1.Rows[0].Cells[0].value

如何在WPF中获取此功能?

2 个答案:

答案 0 :(得分:-1)

您可以使用以下代码获取。

public void DataGridCellValue(object param)
    {
        string clipboard = string.Empty;
        if (param != null)
        {

            if (param is DataGridCell)
            {
                DataGridCell cell = (DataGridCell)param;
                dynamic column = cell.Column as DataGridTextColumn;

                if (cell.Column is DataGridTextColumn)
                    column = cell.Column as DataGridTextColumn;

                if (cell.Content is TextBlock)
                {
                    TextBlock tBlock = cell.Content as TextBlock;
                    clipboard = string.IsNullOrEmpty(tBlock.Text) ? string.Empty : tBlock.Text.Trim();
                }
            }
            else if (param.GetType().IsValueType)
            {
                clipboard = param.ToString();
            }
        }
    }

    #endregion
}

public ICommand DataGridCellValue
    {
        get
        {
            return new DelegatingCommand((object param) =>
            {
                new Action(() =>
                {
                    DataGridCopyToClipBoard(param);
                }).Invoke();
            });
        }
    }

在WPF XAML

中使用这样的绑定
"{Binding CurrentCell, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"

Command和CommandParameter是

Command="{Binding DataGridCellValue}"
CommandParameter="{Binding CurrentCell, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"

答案 1 :(得分:-1)

如果您是WPF新手,请通过以下两个链接开始并了解如何在WPF中完成:

  1. Binding in WPF

  2. DataGrid Data Binaing

  3.   

    作为一个简短的,你真的不需要做   在WPF中gridview1.Rows[0].Cells[0].value,你可以绑定你的   网格到数据源。然后尝试从datasource获取值   集合。(如果你没有看到特定的UI,如:0行的单元格0等)

相关问题