14

我有一个用于编辑数据库信息的 WPF 窗口,它使用实体框架对象表示。当用户关闭窗口时,我想在 Closing 事件中注意信息是否已更改,并显示一个消息框,以将更改保存到数据库。

不幸的是,在编辑失去焦点之前,对当前焦点编辑的更改不会分配给绑定源,这发生在处理 Closing 事件之后的某个时刻。

理想情况下,将有一个例程提交视图层次结构中的所有更改,我可以在检查我的实体是否已被修改之前调用它。我还查找了有关以编程方式清除带有焦点的控件中的焦点的信息,但不知道该怎么做。

我的问题是,这通常是如何处理的?

4

6 回答 6

24

在 WPF 中,您可以更改 aBinding以在修改时更新源,而不是在失去焦点时。这是通过将UpdateSourceTrigger属性设置为PropertyChanged

Value="{Binding Path=MyProperty, UpdateSourceTrigger=PropertyChanged}"
于 2011-01-18T13:51:07.040 回答
8

这应该让你非常接近:



private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    ForceDataValidation();
}


private static void ForceDataValidation()
{
    TextBox textBox = Keyboard.FocusedElement as TextBox;

    if (textBox != null)
    {
        BindingExpression be = textBox.GetBindingExpression(TextBox.TextProperty);
        if (be != null && !textBox.IsReadOnly && textBox.IsEnabled)
        {
            be.UpdateSource();
        }
    }

}


于 2008-10-22T02:32:23.973 回答
6

也许您需要从当前元素中移除焦点

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    FocusManager.SetFocusedElement(this, null);
}
于 2014-10-14T10:47:18.850 回答
1

假设选项卡序列中有多个控件,则以下解决方案似乎是完整且通用的(只是剪切和粘贴)...

Control currentControl = System.Windows.Input.Keyboard.FocusedElement as Control;

if (currentControl != null)
{
    // Force focus away from the current control to update its binding source.
    currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    currentControl.Focus();
}
于 2011-01-18T13:39:39.523 回答
0

另请查看这篇文章中的建议

于 2008-10-22T06:01:36.813 回答
0

最简单的方法是将焦点设置在某处。您可以立即重新设置焦点,但将焦点设置在任何位置都会触发任何类型的控件上的 LostFocus-Event 并使其更新其内容:

IInputElement x = System.Windows.Input.Keyboard.FocusedElement;
DummyField.Focus();
x.Focus();

另一种方法是获取焦点元素,从焦点元素中获取绑定元素,然后手动触发更新。TextBox 和 ComboBox 的示例(您需要添加需要支持的任何控件类型):

TextBox t = Keyboard.FocusedElement as TextBox;
if ((t != null) && (t.GetBindingExpression(TextBox.TextProperty) != null))
  t.GetBindingExpression(TextBox.TextProperty).UpdateSource();
ComboBox c = Keyboard.FocusedElement as ComboBox;
if ((c != null) && (c.GetBindingExpression(ComboBox.TextProperty) != null))
  c.GetBindingExpression(ComboBox.TextProperty).UpdateSource();
于 2008-10-23T14:14:09.143 回答