Sourcecollection count is 0 newitemplaceholder is not shown

1k Views Asked by At

After deleteing all the items in the bound collection, the datagrid.items.count is 1 and the only item in the item collection is newitemplaceholder but the datagrid does not show the newitemplaceholder. This can only occur if the last item is the newitemplaceholder and you attempt to edit it but instead of hitting enter you click the button that fires the delete event.

Since the selecteditem is no longer a newitemplaceholder because of the edit event, the item is considered to be a new item in the sourcecollection.

Before the delete is called, there is an item.count of 2 in the datagrid.

Any help on how to get the newitemplaceholder to show up in this odd situation?

1

There are 1 best solutions below

0
On

I've faced with the same issue, moreover it was happened not only when source collection count is 0, but for any last row in the edit state - once deleted from edit state, new record row in the bottom of the grid disappears. I haven't found anything better than this - pretty rude and not very fast solution, but at least it works for me and currenly that's better than nothing.

Given the DataGrid named grItems, private view model reference _vm having Items property used for data grid binding, the sample code could look like this:

 <DataGrid Name="grItems"
        ItemsSource="{Binding Path=Items}" 
        UnloadingRow="DataGridUnloadingRow">

and code behind:

    private void DataGridUnloadingRow(object sender, DataGridRowEventArgs e)
    {
        grItems.UnloadingRow -= DataGridUnloadingRow;
        grItems.ItemsSource = null;
        grItems.ItemsSource = _vm.Items;
        grItems.UnloadingRow += DataGridUnloadingRow;
    } 

UPDATE

Later I've noticed that this does not work when we need to scroll the grid - I was getting some internal WPF error 'Offset and length were out of bounds...'. Earlier I had a delete button per row that was bound to the command defined on the same level as Items list. So I had to get rid of commands and to use code behind in a view with a little dirty trick - before removing an item from view model collection, I am moving focus somewhere out of the grid and after deletion take the focus back. To my understanding this trick performs some kind of 'commit' of newly added row, and delete action is performed on the row that is not in the edit state.