如何通过提供columnidnex和行索引来获取和设置WPF DataGrid中单元格的值?

时间:2011-08-18 07:33:28

标签: c# .net wpf

请告诉我,如何通过提供columnidnex和行索引来获取和设置WPF DataGrid中单元格的值

由于

2 个答案:

答案 0 :(得分:2)

这并不像在WPF中那样容易,它只是选择可视子项(WPF'Visual'对象类型)。 This blog post很好地解释了如何实现它。谷歌,你可能会发现更多。

答案 1 :(得分:1)

 // Getting Data from Grid Cell 
 string cellContent = ((TextBox)(GetCell(3).Content)).Text; //As I want the value of 3 column

 public DataGridCell GetCell(int column)
        {
            DataGridRow rowContainer = GetRow();

            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

                // Try to get the cell but it may possibly be virtualized.
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                if (cell == null)
                {
                    // Now try to bring into view and retreive the cell.
                    customDataGrid.UCdataGridView.ScrollIntoView(rowContainer, customDataGrid.UCdataGridView.Columns[column]);
                    cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                }
                return cell;
            }
            return null;
        }

 public DataGridRow GetRow()
        {
            DataGridRow row = (DataGridRow)customDataGrid.UCdataGridView.ItemContainerGenerator.ContainerFromIndex(_currentRowIndex);
            if (row == null)
            {
                // May be virtualized, bring into view and try again.
                customDataGrid.UCdataGridView.UpdateLayout();
                customDataGrid.UCdataGridView.ScrollIntoView(customDataGrid.UCdataGridView.Items[_currentRowIndex]);
                row = (DataGridRow)customDataGrid.UCdataGridView.ItemContainerGenerator.ContainerFromIndex(_currentRowIndex);
            }
            return row;
        }

        public static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = v as T;
                if (child == null)
                {
                    child = GetVisualChild<T>(v);
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;
        }

// Setting Data to Grid Cell
if (GetCell(3).Content is TextBlock) // if grid cell is not editable
{
      ((TextBlock)(GetCell(3).Content)).Text = "sometext";
}
else // TextBox  - if grid cell is editable
{
        ((TextBox)(GetCell(3).Content)).Text = "sometext";
}