I have the following DataGrid:
<DataGrid ItemsSource="{Binding EmployeeList}" CanUserAddRows="True" AutoGenerateColumns="False" Margin="0,0,0,90">
<DataGrid.Columns>
<DataGridTemplateColumn Header="CountryCombo2">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=DataContext.CountryList, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
DisplayMemberPath="CountryName"
SelectedItem="{Binding EmployeeCountry, Mode=TwoWay}"
SelectedValue="{Binding EmployeeCountry.CountryId}"
SelectedValuePath="CountryId" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
However, I am unable to add new rows to the DataGrid. Please let me know if I need to provide any additional code.
Update :
Screen 1 : This is the screenshot when the window is just loaded with the hardcoded property values. Now I see the empty new row.
Screen 2 : Here I have added data into the new row with values Rambo and Russia. Now, no matter what I do (tab-out, click in another cell), the next new row is not added. I believe it should be adding a new row.
Screen 3 : Here the newly added row values have disappeared. That is because I double clicked on the thin border between the two empty cells. Now this is pretty weird.
Screen 4 : Now when I click on the Peter cell, the previously entered row data is back but now it is pushed down and a new empty row is inserted before it. This is very strange.
Can anyone please help me understand this behavior of the DataGrid.
In my case,
First ensure your ItemSource
is not using an array
that can't add new item to it,
use something like List
that can add newItem,
Besides, the SomeClass
should have an default constructor takes no parameters like
List<SomeClass>();
public Class SomeClass
{
public SomeClass() { }
}
then the new empty row appear in the bottom of the DataGrid
.
Refer to this answer.