[c#] Adding a Button to a WPF DataGrid

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 or the SubRow.

How do I add a button which will show/Hide the RowDetailsTemplate?

This question is related to c# wpf xaml datagrid

The answer is


XAML :

<DataGrid x:Name="dgv_Students" AutoGenerateColumns="False"  ItemsSource="{Binding People}" Margin="10,20,10,0" Style="{StaticResource AzureDataGrid}" FontFamily="B Yekan" Background="#FFB9D1BA" >
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Click="Button_Click_dgvs">Text</Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    </DataGrid.Columns>

Code Behind :

       private IEnumerable<DataGridRow> 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.


Check this out:

XAML:

<DataGrid Name="DataGrid1">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Click="ChangeText">Show/Hide</Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Method:

private void ChangeText(object sender, RoutedEventArgs e)
{
    DemoModel model = (sender as Button).DataContext as DemoModel;
    model.DynamicText = (new Random().Next(0, 100).ToString());
}

Class:

class DemoModel : INotifyPropertyChanged
{
    protected String _text;
    public String Text
    {
        get { return _text; }
        set { _text = value; RaisePropertyChanged("Text"); }
    }

    protected String _dynamicText;
    public String DynamicText
    {
        get { return _dynamicText; }
        set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null)
        {
            temp(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Initialization Code:

ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to wpf

Error: the entity type requires a primary key Reportviewer tool missing in visual studio 2017 RC Pass command parameter to method in ViewModel in WPF? Calling async method on button click Setting DataContext in XAML in WPF How to resolve this System.IO.FileNotFoundException System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll? Binding an Image in WPF MVVM How to bind DataTable to Datagrid Setting cursor at the end of any text of a textbox

Examples related to xaml

Setting DataContext in XAML in WPF Change color of Button when Mouse is over Implement Validation for WPF TextBoxes Use StringFormat to add a string to a WPF XAML binding How to format number of decimal places in wpf using style/template? How to set DataGrid's row Background, based on a property value using data bindings WPF C# button style How to clear a textbox once a button is clicked in WPF? Add Items to Columns in a WPF ListView Binding ConverterParameter

Examples related to datagrid

How to bind DataTable to Datagrid WPF Datagrid Get Selected Cell Value Wpf DataGrid Add new row How to clear a data grid view Adding values to specific DataTable cells Accessing UI (Main) Thread safely in WPF Date formatting in WPF datagrid How to hide column of DataGridView when using custom DataSource? How can I disable editing cells in a WPF Datagrid? Datagrid binding in WPF