0

I have a Datagrid with SelectionUnit="CellOrRowHeader" set.

With my DataGrid being in the content area of a TabControl, the currently edited row is being discarded when I switch the tab.

I figured when I get the DataRowView of the current row, I can call row?.EndEdit(); (which is being triggered by a enter hit on the keyboard, but can also be called manually) to update the data to source. However, I cant seem to get the current DatarRowView.

How could I tell the DataGrid to update all the currently edited data to source? Is my approach the correct one, and if yes, how do I get the current DataRowView?

If not, how do I tell the DataGrid to finish edit mode and update its new data to source?

Mafii
  • 7,227
  • 1
  • 35
  • 55

1 Answers1

0

This is not a straight solution, however will solve the problem.

One can simply focus another control on the gui, and the DataGrid will commit its changes to the current row. The effect is the same as if you press enter while you edit the DataGrid.

Example:

I have a TabControl. When the TabControl switches the tab, I want the current changes saved.

The xaml of the TabControl:

    <TabControl DockPanel.Dock="Top" 
                x:Name="TabControl" 
                ItemsSource="{Binding Tabs}" 
                ContentTemplateSelector="{StaticResource TabContentTemplateSelector}"
                SelectionChanged="TabControl_OnSelectionChanged"
                IsSynchronizedWithCurrentItem="True">
....

Note the SelectionChanged="TabControl_OnSelectionChanged" but it can be any other event on any other control you want. Even a command, whatever.

What you then want, is simply focus another gui element:

private void TabControl_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
  // focus the tab control to lose focus on datagrids - they will then commit changes if possible.
  TabControl.Focus(); // my TabControl is x:Name="TabControl", Focus sets the focus
}

As mentioned, the effect is exactly the same as if you press enter while editing the cell.

Mafii
  • 7,227
  • 1
  • 35
  • 55
  • I tested this, but it is NOT so. The datagrid stays in edit mode. – rabejens Nov 27 '16 at 12:40
  • Hmm. It worked for what I needed. What do you mean with stays in edit mode? The question was about forcing it to update to source, not exiting edit mode. You can call `Cell.EndEdit()` if you wanna exit the edit mode. – Mafii Nov 27 '16 at 15:35
  • Maybe my issue is a bit different. I have a tab control with some datagrids in there, and when I switch tabs, I want the data grid I am currently editing to commit its changes. Simply using `tabControl.Focus()` did not do the trick for me, I explicitly had to commit the changes of the respective datagrids. – rabejens Nov 27 '16 at 18:51
  • @rabejens Interesting. Maybe it has to do with different binding and focus settings, but glad it worked for you in the end. – Mafii Nov 28 '16 at 10:30