WPF RaisePropertyChanged事件失去焦点 [英] WPF RaisePropertyChanged event on lost focus
问题描述
我有一个运行良好的C#WPF MVVM应用程序.
I have a C# WPF MVVM application that works fine.
唯一的问题是当我修改文本框并单击菜单时.如果我不单击其他控件就这样做,则不会触发view-> viewmodel事件,因为文本框没有失去焦点.如果我错了,请纠正我,但我认为RaisePropertyChanged仅在LostFocus(或OnBlur或任何类似事件)上触发.
The only problem is when I modify a textbox and click on the menu. If I do that without clicking on another control, the view->viewmodel event is never fired because the textbox hasn't lost focus. Correct me if I am wrong, but I think the RaisePropertyChanged is only fired on LostFocus (or OnBlur, or any similar event).
因此,在编辑文本框后立即单击菜单保存按钮会导致视图模型使用旧值保存数据.
So, clicking on the menu save button right after editing the textbox causes the viewmodel to save the data using old values.
因此,恢复:
此序列工作正常:
- 编辑文本框
- 点击另一个控件
- 触发RaisePropertyChanged,更新视图模型
- 单击菜单上的保存"按钮
- 以正确的值保存的数据
此序列给我一个错误:
- 编辑文本框
- 单击菜单上的保存"按钮
- 以正确的值保存的数据
如何解决这个问题?
推荐答案
这是WPF和WinForms中TextBoxes的常见陷阱.您可以通过指示绑定系统通过对TextBox的每次更改而不是在失去焦点时更新VM来解决此问题.为此,请将绑定的UpdateSourceTrigger
设置为PropertyChanged
.每当TextBox为其Text
属性引发PropertyChanged
事件时,都会将其写回VM.
This is a common gotcha with TextBoxes in both WPF and WinForms. You can get around this by instructing the binding system to update the VM with every change to the TextBox instead of when it loses focus. To do this, set the UpdateSourceTrigger
of the binding to PropertyChanged
. This will write back to the VM any time the TextBox raises the PropertyChanged
event for its Text
property.
<TextBox Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
这篇关于WPF RaisePropertyChanged事件失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!