Search code examples
c#wpfdatagridtabcontroldatarowview

Update datagrid row that is in edit state to source from code


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?


Solution

  • 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.