Suspend Databinding of Controls

前端 未结 6 1342
终归单人心
终归单人心 2021-02-05 13:00

I have a series of controls that are databound to values that change every second or so. From time to time, I need to \"pause\" the controls, so that they do not update their d

6条回答
  •  不思量自难忘°
    2021-02-05 13:25

    My solution ended up as follows to prevent the text updating while the user is trying to change it.

    XAML:

    
    
    

    Code behind:

        private void TextBox_OnGotFocus([CanBeNull] object sender, [CanBeNull] RoutedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb == null) return;
            BindingExpression expression = tb.GetBindingExpression(TextBox.TextProperty);
            if (expression == null) return;
            // disable updates from source
            BindingOperations.ClearBinding(tb, TextBlock.TextProperty);
            tb.SetBinding(TextBox.TextProperty, new Binding(expression.ParentBinding.Path.Path) { Mode = BindingMode.OneWayToSource, UpdateSourceTrigger = UpdateSourceTrigger.Explicit , FallbackValue = tb.Text});
        }
    
        private void TextBox_OnLostFocus([CanBeNull] object sender, [CanBeNull] RoutedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb == null) return;
            BindingExpression expression = tb.GetBindingExpression(TextBox.TextProperty);
            if (expression == null) return;
            // send current value to source
            expression.UpdateSource();
            // enable updates from source
            BindingOperations.ClearBinding(tb, TextBlock.TextProperty);
            tb.SetBinding(TextBox.TextProperty, new Binding(expression.ParentBinding.Path.Path) { Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.LostFocus });
        }
    

    Note that I assign the current Text as the fallback value of the OneWayToSource binding to have a start value (otherwise the text field would be empty once focused)

提交回复
热议问题