c# - WPF. Button.IsDefault = true. Without UpdateSourceTrigger=PropertyChanged
问题描述
I have many forms with a lot of textboxes. And I want to add to that forms a button with IsDefault = true
. Then fill any property and press enter. If I will not set UpdateSourceTrigger=PropertyChanged
on textbox, it will not see my input.
The problem is that I do not want to add UpdateSourceTrigger=PropertyChanged
to each textbox
, combobox
, checkbox
, and etc.
Is there any way to trigger everything to write it's data to the source without adding UpdateSourceTrigger=PropertyChanged
?
解决方案
在 Window/UserControl 中的每个控件(TextBox、CheckBox 等)的单击事件处理程序中调用 BindingExpression.UpdateSource 方法,如下所示:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) {
this.UpdateSourceTrigger(this);
MessageBox.Show($"Field1: {this.vm.Field1}\nField2: {this.vm.Field2}\nField3: {this.vm.Field3}");
}
public void UpdateSourceTrigger(UIElement element) {
if (element == null) return;
var children = LogicalTreeHelper.GetChildren(element);
foreach (var e in children) {
if (e is TextBox txtBox) {
var binding = txtBox.GetBindingExpression(TextBox.TextProperty);
binding?.UpdateSource();
}
if (e is CheckBox chkBox) {
var binding = chkBox.GetBindingExpression(CheckBox.IsCheckedProperty);
binding?.UpdateSource();
}
// add other types, like ComboBox or others...
// ...
this.UpdateSourceTrigger(e as UIElement);
}
}
推荐阅读
- grammar - T-SQL 语法分析器规则与自身相互左递归
- reactjs - 如何在 React 中使用多个不间断空格?
- python - 使用 smptlib 发送的电子邮件缺少主题行
- c# - 如何使用 Eclipse 构建 Antlr4 C# 语法?
- java - 假阳性声纳问题
- javascript - 发出新的 websocket 请求时取消当前的 websocket 处理
- angular - 使用Angular 7获取“无法读取未定义的属性'http'”
- audio - .ts 音频文件能否在追加模式下使用 cat 命令组合得到 .mp3 文件
- kubernetes - 如何为容器设置正确的 cpu millicores?
- javascript - 遍历列表并插入对象数组