【问题标题】:How to get cell data value of Datagrid in WPF?如何在WPF中获取Datagrid的单元格数据值?
【发布时间】:2016-04-07 06:49:14
【问题描述】:

我对 WPF 非常陌生,我想制作一个带有Datagrid 控件的数据输入表单。我被困住了,如何获取单元格数据值以将它们存储到数据库中?

就像在 windows 中一样,我们曾经通过gridview1.Rows[0].Cells[0].value 来获取它。

如何在 WPF 中得到这个?

【问题讨论】:

    标签: wpf xaml wpf-controls wpfdatagrid datagridcell


    【解决方案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}}"
    

    【讨论】:

      【解决方案2】:

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

      1. Binding in WPF

      2. DataGrid Data Binaing

      简而言之,你真的不需要做 gridview1.Rows[0].Cells[0].value 在 WPF 中,你可以绑定你的 网格到数据源。然后尝试从数据源中获取值 集合。(如果您没有查看特定于 UI 的内容,例如:第 0 行的单元格 0 等)

      【讨论】:

      • 我想要一个空白的 Datagrid 供用户输入数据,然后将其保存在数据库中。为此,我将空 Datatable 绑定到 Datagrid 并留下几个文本框供用户输入和 1 个按钮,它将向网格添加文本框值。对于保存,我将数据网格的数据上下文分配给 Datatable,并对 Datatable 本身进行了进一步的研究,将数据保存到数据库中。现在请告诉我..这是 WPF 的好习惯吗????我怀疑是这样。
      • @AeshaPatel 虽然你已经给出了这个描述,但我有很多问题,比如为什么用户在文本框中输入值,然后你使用按钮的事件来用这些值填充网格。你不能只是用户在网格本身中输入文本。此外,您不需要将任何内容分配回数据表,只需将您的数据表绑定为 grid'e itemsource,网格中的任何新数据都将反映回您的数据表,在 WPF 中不需要显式代码。如果你也给我一些代码,我会更好地告诉你。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多