WPF:数据绑定选中新选项卡时,TabControl不提交更改 [英] WPF: Data bound TabControl doesn't commit changes when new tab is selected

查看:536
本文介绍了WPF:数据绑定选中新选项卡时,TabControl不提交更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TabControl,其中每个Tab和它的内容是数据绑定到一个ObservableCollection:

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>

如果我点击Tab 1,然后在文本框中键入内容, TextBox失去焦点,我输入到文本框中的新数据将被提交到ObservableCollection项。

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.

但是,如果我在TestBox中输入数据,然后立即点击在另一个选项卡上,数据从不提交。此外,当我回到数据,它不再设置为我输入的内容。

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

我所做的是安装 SelectionChanged 事件:

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



在TabControl上调用Focus()会使TextBox失去焦点和提交数据。我这样做,因为我有其他控件,如DatePicker - 表现出类似的行为。

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.

推荐答案

这个问题在这里很好地描述:WPF绑定:使用LostKeyboardFocus而不是LostFocus作为UpdateSourceTrigger 非常有趣看到从微软的家伙知道这个问题几年,但仍然没有固定。
也是一个很大的讨论:保存前的WPF数据绑定

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

这个黑客工程:

    <TabControl SelectionChanged="OnSelectionChanged">

和codebehind:

And codebehind:

    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (Keyboard.FocusedElement is TextBox)
            Keyboard.FocusedElement.RaiseEvent(new RoutedEventArgs(LostFocusEvent));
    }

这篇关于WPF:数据绑定选中新选项卡时,TabControl不提交更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆