Search code examples
wpfwpf-controlswpfdatagrid

set ItemTemplate for specific column of DataGrid


I have a WPF DataGrid and it is bound to List<Person> people.

public class Person
{
    public string Name{get;set;}
    public string LastName{get;set;}
    public string Address{get;set;}
    public int Age{get;set;}
}

public void ShowPeople()
{
     myDataGrid.ItemsSource = people;
}

It shows everything fine, but I want to show Address in TextBox inside the DataGrid.

I changed XAML code to this:

   <DataGrid x:Name="myDataGrid">
        <DataGridTemplateColumn Header="Address">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Address}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid>

this is not working. It is giving me an error.

Items collection must be empty before using ItemsSource.

Please help. Thanks,


Solution

  • You are missing the Columns property in your XAML:

    <DataGrid x:Name="myDataGrid">
        <DataGrid.Columns> <-- This is missing in your code!
            <DataGridTemplateColumn Header="Address">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding Path=Address}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>