So to give you an Example, first create a Model
public class User
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
then in your Code-Behind File create an ObservableCollection of that Model
private ObservableCollection<User> _myUsers;
public ObservableCollection<User> MyUsers
{
get
{
if (_myUsers == null)
{
_myUsers = new ObservableCollection<User>();
}
return _myUsers;
}
}
and now you can bind your DataGrid to this Property
<DataGrid Grid.Row="1" Name="dataGridUser" ItemsSource="{Binding MyUsers}" AutoGenerateColumns="True"/>
and don´t forget to set the DataContext
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"></Window>
if you add a new User to the ObservableCollection MyUsers it will immediately be displayed in your DataGrid, but if you change the FirstName of a existing User it will not display the changes. To do this you must implement INotityPropertyChanged in your Model.
But if you plan to develop a more complex Application I would recommend to take a look at the MVVM-Pattern.
Personally I like the MVVM Light Toolkit this Video should give you a good Idea what MVVM is all about.
ItemsSourceshould have a binding like{Binding MyItems}whereMyItemswould be anObservableCollectionand you would have it as a public property in whatever data source you have active.