如何取得DataGrid 中的TextBox

  • 2640
  • 0
  • WPF
  • 2016-06-29

摘要:如何取得DataGrid 中的TextBox


 private void btn2_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < this.dgAQL_DEF.Items.Count; i++)
            {
                int column = 0;
                DataGridRow row = (DataGridRow)this.dgAQL_DEF.ItemContainerGenerator.ContainerFromIndex(i);  //取得DataGrid中某一個Row內的容器
                if (row != null)
                {
                    DataGridCellsPresenter presenter = GetVisualChild(row);  //從DataGridRow中取得DataGridCellsPresenter
                    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);  //取得下一個容器
                    TextBox text = GetVisualChild(cell);  //取出容器中的TextBox
                }
            }
        }


 public  T GetVisualChild(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)  //當v轉型失敗時為null
                {
                    child = GetVisualChild(v);  //取子視覺物件下的T 型態
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;  
        }