Search code examples
wpfsilverlightwpfdatagrid

How to get a control inside a wpf datagrid


i have a data-grid with several rows. Inside every row the first column is a button. I have the row index. Let say my row index is 7. Now i want to get the button inside the row 7 and changed its content.

How do i get this button control inside a particular row of a datagrid and change its value?


Solution

  • Perhaps, the below code solve your problem.

    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Click="ShowHideDetails">Details</Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    

    In Codebehind C# access the control

    private void ShowHideDetails(object sender, RoutedEventArgs e)
            {
                // You can access the button and do whateve the changes you want
                Button objMyButton = null;
                if (sender is Button)
                {
                    objMyButton = (sender as Button);
    
                }
    
                //You can access the parent object which means corresponding DataGridRow and do whatever you want
    
                for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
                    if (vis is DataGridRow)
                    {
                        var row = (DataGridRow)vis;                 
                        break;
                    }
            }