If you wish to do it with completely binding, (without setting the itemsource in codebehind),find the below solution
Create a class with the properties you required like Name and ID which should implement
INotifyPropertyChanged
public class UserInfo: INotifyPropertyChanged
{
private string _name;
public string Name {
get { return _name; }
set { _name = value; onPropertyChanged(this, "Name"); }
}
public int _ID;
public int ID {
get { return _ID; }
set { _grade = value; onPropertyChanged(this, "ID"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void onPropertyChanged(object sender, string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
}
}
}
Create another class which holds the collection of UserInfo and set this class as a DataContext to datagrid
public class DataGridSource : INotifyPropertyChanged
{
public DataGridSource()
{
DGItemsSource = new ObservableCollection<userinfo>();
}
private ObservableCollection<userinfo> _ItemsSource;
public ObservableCollection<userinfo> DGItemsSource
{
get { return _ItemsSource; }
set { _ItemsSource = value; onPropertyChanged(this, "DGItemsSource"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void onPropertyChanged(object sender, string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
}
}
}
Modify your XAML like this
<datagrid autogeneratecolumns="False" height="311" itemssource="{Binding DGItemsSource}" horizontalalignment="Right" name="datagrid1" verticalalignment="Center" width="202" selectionchanged="dataGrid1_SelectionChanged" DataContext="{Binding DGSource}" CanUserAddRows="{Binding ElementName=dataGrid1}" CanUserDeleteRows="{Binding ElementName=dataGrid1}" MinRowHeight="1" Margin="0,-2,0,0" FontWeight="Bold">
<datagrid.columns>
<datagridtextcolumn header="Name" width="100" canuserresize="False" binding="{Binding Name}" canuserreorder="False" />
<datagridtextcolumn header="ID" width="100" canuserresize="False" binding="{Binding ID}" canuserreorder="False" />
</datagrid.columns>
</datagrid>
Modify youe constructor to
public MainWindow()
{
InitializeComponent();
datagrid1.DataContext = new DataGridSource();
SetInitialValues();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
(datagrid1.DataContext as DataGridSource).DGItemsSource.Add(new UserInfo() { Name = textbox1.Text, ID = Convert.ToInt32(textbox2.Text) });
}
Note:Use exception handling wherever required( converting textbox2.Text to int)