Search code examples
c#wpfdatagrid.net-6.0itemsource

AddingItemEvent not adding the item to the ItemSource c#


I created a pretty straight forward desktop application with WPF and net6.0. The application contains a DataGrid with the following XAML code:

            <DataGrid x:Name="tblTopics" 
                      CanUserAddRows="True" 
                      AddingNewItem="tblTopics_AddingNewItem"
                      />

The binding was done during the initalization of the application with the following statement:

        tblTopics.ItemsSource = Topics;

Where Topics is an ObservableList containing the class Topic. Everything works as intended and all rows are properly loaded in the application. Also, if I edit some rows, the changes are correctly transfered to the ItemSource.

However, if a new item is added via clicking in the empty row at the bottom, this change or rather addition is not reflected in the ItemSource. My code for AddingNewItem looks as follows:

    private void tblTopics_AddingNewItem(object sender, AddingNewItemEventArgs e)
    {
        Debug.WriteLine("New Topic added...");
        Topic newTopic = new Topic(TopicType.NO_TYPE, "Title", "Description", DateTime.Now, "Responsible");
        e.NewItem = newTopic;
    }

Interestingly, if I add the item "manually" via code upon a click on a button to the ItemSource, the item will be displayed in the application as well. No problem there. But what am I doing wrong with the above approach? Why is the newly added item not being transferred to the ItemSource?


Solution

  • By accident I found the solution to my problem, thx to WPF DataGrid - Event for New Rows?

    The issue is that "Objects are persisted (inserted or updated) when the user leaves a row that he was editing. Moving to another cell in the same row updates the corresponding property through data binding, but doesn't signal the Model (or the Data Access Layer) yet. The only useful event is DataGrid.RowEditEnding. This is fired just before committing the modified row."

    So accordingly, upon the RowEditEnding event, I check whether the user committed a change and if so, I add the rowItem to the itemsource.

        private void tblTopics_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            {    
                if (e.EditAction == DataGridEditAction.Commit)
                {
                    var newItem = e.Row.DataContext as ItemSourceDataType;
                    if (!MyItemSource.Contains(newItem)){
                         //add newItem to itemsource
                    }
                }
            }
        }