WPF中的EndEdit等价物

Thi*_*ies 6 .net c# data-binding wpf textbox

我有一个包含TextBox的WPF窗口.我已经实现了一个在Crtl-S上执行的Command,它保存了窗口的内容.我的问题是,如果文本框是活动控件,并且我在文本框中有新编辑的文本,则不会提交文本框中的最新更改.我需要从文本框中跳出来获取更改.

在WinForms中,我通常会在表单上调用EndEdit,并且所有挂起的更改都会被提交.另一种方法是使用onPropertyChange绑定而不是onValidation,但我宁愿不这样做.

什么是WPE等效于EndEdit,或者在这种情况下使用的模式是什么?

谢谢,

Thi*_*ies 6

基于Pwninstein答案,现在我已经实现了EndEdit我的WPF查看/窗口将查找绑定,并迫使它们的更新公共类,下面的代码;

代码如下;

private void EndEdit(DependencyObject parent)
{
    LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();
    while (localValues.MoveNext())
    {
        LocalValueEntry entry = localValues.Current;
        if (BindingOperations.IsDataBound(parent, entry.Property))
        {
            BindingExpression binding = BindingOperations.GetBindingExpression(parent, entry.Property);
            if (binding != null)
            {
                binding.UpdateSource();
            }
        }
    }            

    for(int i=0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);
        this.EndEdit(child);
    }
}

protected void EndEdit()
{
    this.EndEdit(this);
}
Run Code Online (Sandbox Code Playgroud)

在我的Save命令中,我现在只是调用该EndEdit方法,而我不必担心其他程序员选择绑定方法.


Mar*_*ter 5

为了避免需要按 Tab 键离开的问题,您只需更改控件绑定的 UpdateSourceTrigger 属性即可。请尝试以下操作:

<TextBox.Text>
    <Binding Path="MyProperty" UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
Run Code Online (Sandbox Code Playgroud)

这告诉 WPF 在 Text 属性发生更改时更新支持对象。这样,您就无需担心按 Tab 键离开。希望这可以帮助!

编辑:

以下 SO 问题的可接受答案提供了一种自动运行页面验证规则的方法。您可以修改它以对所有 BindingExpression 对象调用 UpdateSource()。

关联


Dav*_*son 5

您可以使用以下代码强制更新特定绑定:

var bindingExpression = txtInput.GetBindingExpression(TextBox.TextProperty);
bindingExpression.UpdateSource();
Run Code Online (Sandbox Code Playgroud)

更普遍地这样做很困难,因为没有通用的方法来获取所有绑定,也不一定要全部更新它们.