Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Data bound TabControl doesn't commit changes when new tab is selected

Tags:

wpf

c#-4.0

I've got a TabControl where each Tab and it's contents are databound to an ObservableCollection:

<TabControl ItemsSource="{Binding Path=.}">
    <TabControl.ContentTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Path=propertyValue}" />
        </DataTemplate>
    </TabControl>
</TabControl>

If I were to click on Tab 1, then type something into the text box and hit tab so that the TextBox loses focus, the new data that I typed into the textbox would be committed to the ObservableCollection item.

However, if I type data into the TestBox and then immediately click on another tab, the data is never committed. Plus, when I go back to the data, it's no longer set to what I had typed in.

Anyone know a way to force the data to get committed before the current tab is changed?

UPDATE & FIX

What I did was wired up the SelectionChanged event:

private void tabData_SelectionChanged(object sender, SelectionChangedEventArgs e) {
    theTabControl.Focus();         
}

Calling Focus() on the TabControl makes the TextBox lose focus and commit data. I did this because I have other controls -- such as DatePicker -- which exhibit a similar behavior. This is sort-of a catch all.

like image 437
bugfixr Avatar asked Apr 18 '12 11:04

bugfixr


1 Answers

This issue is well described here: WPF Binding: Use LostKeyboardFocus instead of LostFocus as UpdateSourceTrigger Very interesting to see that guys from Microsoft knows about this problem for several years but still not fixed it. Also a big discussing here: WPF Databind Before Saving

This hack works:

    <TabControl SelectionChanged="OnSelectionChanged">

And codebehind:

    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (Keyboard.FocusedElement is TextBox)
            Keyboard.FocusedElement.RaiseEvent(new RoutedEventArgs(LostFocusEvent));
    }
like image 172
asktomsk Avatar answered Oct 25 '22 17:10

asktomsk