Sunday, September 25, 2011

Why is my Silverlight DataForm acting like that?

The other day, as I was using Silverlight, I put a DataGrid inside of a DataForm. Seems innocent enough, right? Specifically, what I wanted to accomplish was to allow users to add elements to a DataGrid with drag and drop functionality. Therefore, there were two DataGrids - one that the user dragged from, and the other that would receive the drop event. What I noticed, though, was that the added elements were not being saved.

We are using WCF RIA services, so I first assumed that I had created my composition objects incorrectly, and so I spent quite a bit of time looking into and verifying that code. After adding more and more breakpoints, I discovered that the WCF RIA service call was not to blame - the added elements were not even in the Submit operation, and so they were being removed sometime before the Submit was called.

Next, life got even more strange - if I edited one of the DataFields on the DataGrid, and then I dragged an item over, everything saved correctly. This left me quite puzzled. Then, eventually, a co-worker helped me discover the problem (which I thought was strange enough to warrant a blog post - maybe this will help other people (or even myself) next time one of us runs into this situation).

A Silverlight DataForm Rejects changes on EditEnded.

What? Yeah, I thought that this was quite strange. Why was I hitting this event? My "Save" button was not in the DataGrid! However, once you know this, it is easy enough to fix. Handle the EditEnding event on the DataForm and mark the event canceled:

private void DataForm_EditEnding(object sender, DataFormEditEndingEventArgs e)
       e.Cancel = true;

Done! Now my DataForm stopped rejecting my changes.