Search code examples
c#wpfdatagridviewwpfdatagrid

Create a DataGrid in WPF with column type equal with DataGridViewButtonColumn of WinForm


In WinForm i can programmatically add Rows on a DataGridView column(s) with loop, let say like this

private void rowsAdder()
{
    for(int u = 0; u<= 10; u++)
    {
         classSelect.Rows.Add("Number " + u);
         //classSelect is a name of a DataGridView, where the first column is a DataGridViewButtonColumn
    }
}

Then my questions are :

-What are the equal ways in WPF to add Rows in a DataGrid (using looped Rows.Add() etc) ?

-How to set the column type into ButtonColumn ?

If this help, i'm using .NET 4.5


Solution

  • Here is an extremely simple example :

    <Window x:Class="DataGridUpdateSourceTriggerOneWay.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataGridUpdateSourceTriggerOneWay"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid x:Name="DataGrid1" 
                  IsReadOnly="False"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False"
                  ItemsSource="{Binding data}">
    
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Field">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding Path=Name, Mode=TwoWay, 
                        UpdateSourceTrigger=PropertyChanged}" Width="Auto"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Length of Field">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding Path=Length, Mode=TwoWay, 
                        UpdateSourceTrigger=PropertyChanged}" Width="Auto"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
    

    Here is your DataGrid, its ItemsSource bounded to data which exists in the codebehind below:

    public partial class MainWindow : Window
    {
        public ObservableCollection<Data> data { get; set; }
    
        public MainWindow()
        {
            InitializeComponent();
            data = new ObservableCollection<Data>();
            data.Add(new Data() { Name = "Data1", Length = 1 });
            data.Add(new Data() { Name = "Data2", Length = 2 });
            this.DataContext = this;
        }
     }
    

    Collections need to inform their bound-view elements that their contents have changed (items added or removed ), that's the job of the ObservableCollection<Data>.

    And here is the Data class:

    public class Data : INotifyPropertyChanged
    {
        private string _Name;
    
        public string Name
        {
            get { return _Name; }
            set
            {
                _Name = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }
    
        private int _Length;
    
        public int Length
        {
            get { return _Length; }
            set
            {
                _Length = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Length"));
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged = delegate { };
    }
    

    The INotifyPropertyChanged interface is part of an implementation of the Observer pattern for a specific purpose: to inform subscribers that the value of a property on the publisher has just changed. So, changing those two propeties, Name or Length on the instances existing the collection will result in a View update.

    Let me know if you need more details about this.

    Oh, i forgot, how would you add a new row ? Just handle a Click event for a Button placed somewhere on the View and add a new Data instance to data collection.

    Ex:

    data.Add(new Data() { Name = "Data3", Length = 3 });