我有一个用于编辑数据库信息的WPF窗口,它使用Entity Framework对象表示.当用户关闭窗口时,我想在Closing事件中注意信息是否已更改并显示一个消息框,用于将更改保存到数据库.
不幸的是,在编辑失去焦点之前,对当前焦点编辑的更改不会分配给绑定源,这会在处理Closing事件之后的某个时刻发生.
理想情况下,在检查我的实体是否已被修改之前,会有一个例程提交我可以调用的视图层次结构中的所有更改.我也在寻找有关以焦点方式清除控件焦点的信息,但无法弄清楚如何去做.
我的问题是,这通常是如何处理的?
M. *_*ley 22
在WPF中,您可以更改a Binding以更新修改源,而不是失去焦点.这是通过将UpdateSourceTrigger属性设置为PropertyChanged:
Value="{Binding Path=MyProperty, UpdateSourceTrigger=PropertyChanged}"
Run Code Online (Sandbox Code Playgroud)
这应该让你非常接近:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
也许您需要从当前元素中移除焦点
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
FocusManager.SetFocusedElement(this, null);
}
Run Code Online (Sandbox Code Playgroud)