首页 > 解决方案 > 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?

标签: c#wpf

解决方案


在 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);
    }
}

推荐阅读