AWG Blogs

Sunday, September 9, 2012

Set ClickMode to Press to Avoid Losing Click Event in DataGrid Column But Note Caveats

For some reason, I was losing the click event for a button in a DataGridTemplateColumn; i.e. the click event (and associated command) would not fire after editing another cell and immediately clicking the (delete) button in the far left column. Setting the ClickMode to Press (rather than the default of Release) appears to fix the issue; i.e. once that is done, the event fires, and I do not have to click Delete twice. There are a couple of steps to take in addition if the DataGrid is bound to a PagedCollectionView that you intend to Refresh() immediately, i.e. within the called Command. These are so as to avoid the error:
An exception of type 'System.InvalidOperationException' occurred in System.Windows.Data but was not handled in user code

Additional information: 'Refresh' is not allowed during an AddNew or EditItem transaction.
1) Add a GotFocus="Button_GotFocus" to the event with method:
        private void Button_GotFocus(object sender, RoutedEventArgs e)
        {
            dataGrid1.CommitEdit(DataGridEditingUnit.Row, true);
        }
Evidently, GotFocus fires before Click here, so it is the place to exit Edit mode.
2) Wrap the pagedCollectionView.Refresh() call in an asynchronous call:

    Deployment.Current.Dispatcher.BeginInvoke(
    () =>
    {
        pagedCollectionView.Refresh();
    });
Evidently, the asynch call delays the refresh long enough so that the row can exit edit mode. These are workarounds that signal a compromise with MVVM and elegance in general, but until I find a better solution, it is what it is.

No comments:

Post a Comment