1. 程式人生 > >wpf 中獲取datagrid中的值

wpf 中獲取datagrid中的值

        public static void SetDataGridCellIsEnabled(DataGrid datagrid, int rowIndex, int[] cellIndexArray, bool IsEnabled)
        {
            for (int index = 0; index < cellIndexArray.Length; index++)
            {
                DataGridCell currentCell = GetDataGridCell(datagrid, rowIndex, cellIndexArray[index]);
                if (currentCell != null)
                {
                    currentCell.IsEnabled = IsEnabled;

                    這行程式碼是隱藏單元格

                    Button button1= currentCell.ChildrenOfType<Button>();

                     這行程式碼是得到模板控制元件裡的子控制元件
                }
            }
        }

        public static DataGridCell GetDataGridCell(DataGrid datagrid, int rowIndex, int columnIndex)
        {
            try
            {
                DataGridRow rowContainer = GetDataGridRow(datagrid, rowIndex);
               
                if (rowContainer != null)
                {
                    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

                    這行程式碼是通過行得到單元格

                    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);

                    這行程式碼是通過index得到具體的單元格


                    if (cell == null)
                    {
                        datagrid.ScrollIntoView(rowContainer, datagrid.Columns[columnIndex]);
                        cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
                    }

                    return cell;
                }
            }
            catch
            {
                return null;
            }
            return new DataGridCell();
        }

        public static DataGridRow GetDataGridRow(DataGrid datagrid, int rowIndex)
        {
            DataGridRow row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);

            這行程式碼的作用是得到datagrid的一行


            if (row == null)
            {
                datagrid.UpdateLayout();
                //datagrid.ScrollIntoView(datagrid.Items[rowIndex]);
                row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
            }
            return row;
        }

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