WPF DataGrid 对行中单元格的访问

本文介绍了两种在WPF应用程序中使用DataGrid组件的方法。第一种是在单元格编辑准备阶段获取选中行的数据;第二种是在选择更改时通过查找单元格内容来获取信息。这两种方法都展示了如何有效地从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;
        }

 

转载于:https://www.cnblogs.com/wangsu/archive/2013/01/08/WPF_DataGrid_Cell.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值