Adding a Button to a WPF DataGrid

后端 未结 3 1406
[愿得一人]
[愿得一人] 2020-12-13 03:49

I want to create a DataGrid control in WPF in which there is a button in the first cell of each row. Clicking this button will show RowDetailsTemplate

3条回答
  •  醉话见心
    2020-12-13 04:04

    XAML :

    
                    
                        
                            
                                
                                    
                                
                            
                        
                        
    

    Code Behind :

           private IEnumerable GetDataGridRowsForButtons(DataGrid grid)
    { //IQueryable 
        var itemsSource = grid.ItemsSource as IEnumerable;
        if (null == itemsSource) yield return null;
        foreach (var item in itemsSource)
        {
            var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
            if (null != row & row.IsSelected) yield return row;
        }
    }
    
    void Button_Click_dgvs(object sender, RoutedEventArgs e)
    {
    
        for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
            if (vis is DataGridRow)
            {
               // var row = (DataGrid)vis;
    
                var rows = GetDataGridRowsForButtons(dgv_Students);
                string id;
                foreach (DataGridRow dr in rows)
                {
                    id = (dr.Item as tbl_student).Identification_code;
                    MessageBox.Show(id);
                     break;
                }
                break;
            }
    }
    

    After clicking on the Button, the ID of that row is returned to you and you can use it for your Button name.

提交回复
热议问题