WPF DataGrid 對行中單元格的訪問

第一種方法:

dataGridFirst.PreparingCellForEdit += new EventHandler<DataGridPreparingCellForEditEventArgs>(dataGridFirst_PreparingCellForEdit);

  void dataGridFirst_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
  {
  Suppose this list(get and set values)
  //var myValue = dataGrid1.SelectedItem[0].ToString(); 
  ClientsList selectedrow = ClientsList)dataGridFirst.SelectedItem;
  string Clientname = selectedrow.Name;
  int Clientid = selectedrow.ClientID;
  
  }

第二種方法:

private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) 
        {     
            DataGrid dataGrid = sender as DataGrid;  
            if (e.AddedItems!=null && e.AddedItems.Count>0)  
            {       
                // find row for the first selected item     
                DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(e.AddedItems[0]);    
                if (row != null)   
                {          
                    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);   
                    // find grid cell object for the cell with index 0       
                    DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(0) as DataGridCell;      
                    if (cell != null)     
                    {             
                        Console.WriteLine(((TextBlock)cell.Content).Text);         
                    }     
                }   
            }
        }

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;
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章