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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With