How to bind data in a DataGrid in WPF?
One way to bind data to a DataGrid control in WPF is by using the following method:
- By using the ItemsSource property, you can bind a collection to the DataGrid’s ItemsSource property, for example:
 
dataGrid.ItemsSource = myCollection;
myCollection is a collection that implements the IEnumerable interface, it can be an ObservableCollection, List, or other collection type.
- Incorporating Binding in XAML allows for data to be connected to a DataGrid using Binding syntax within the XAML code.
 
<DataGrid ItemsSource="{Binding MyCollection}" />
MyCollection is a property in the ViewModel that needs to implement the INotifyPropertyChanged interface.
- With the AutoGenerateColumns property, you can automatically generate columns for the DataGrid by setting the property to true and binding the data. For example:
 
<DataGrid ItemsSource="{Binding MyCollection}" AutoGenerateColumns="True" />
This method automatically generates columns based on the bound data type, but may not meet specific requirements. For more flexible data binding, you can manually define the columns of the DataGrid.
- You can customize columns and bind data manually by using DataGridTemplateColumn, for example:
 
<DataGrid ItemsSource="{Binding MyCollection}">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Name">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Age">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Age}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
This allows the styles and data binding methods of each column to be defined according to the requirements.