Practice Experience about DataGrid in WPF

Our experience is started from this error in datagrid binding. DataGrid Item resource is binding to SideGames, and Program would like to accept customer new input and set up a new Sidegame.

I monitor the celleditEnding event to update Sidegames and do view update. SelectedItem binding to SelectedSideGame, SelectedSideGame is not changed when SelectedItem is changed when I start to debug. This is very strange.

To solve this problem ,I add SelectionChanged event to handle SelectedSideGame property. Get new item from parameter e (SelectionChangedEventArgs) and set this item to SelectedSideGame, However sometimes e.newItem is not SideGame Object ,is ElementHolder,which cause Conversion failed. That confuse me a lot.

Then I changed the property SelectedItem to CurrrentItem ,and binding to same object, which solve the problem (SelectedSideGame changed with selection changed.)But I still have same Error shown on the start of blog.

struggle for long time, the error is disappear when changed selectionUnit from Fullrow to Cell. However this is not solution,because selection should be fullrow instead of Cell.

Here we can see the difference between selectedItem and currentItem in DataGrid ,If selection mode is single , we can set IsSynchronizedWithCurrentItem = true to make sure selectedItem is equal CurrentItem.

After analyzing the flow, I removed SelectionChanged event, and use “Initialing new Item ” event to handle flow when user click datagrid to generate new rows,I created new object with default value and do binding collection update .

By the way, when we use cellEditending event, CommitEdit method is preferred to fire before updating view.

Leave a comment