Suspend Databinding of Controls

前端 未结 6 1341
终归单人心
终归单人心 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:22

    First of all you need create explicit binding:

    Binding binding = new Binding("Content");
    binding.Source = source;
    binding.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
    binding.Mode = BindingMode.TwoWay;
    txtContent.SetBinding(TextBox.TextProperty, binding);
    

    Then when you need pause twoway binding you need destroy old binding and create new oneway binding with explicit trigger(in this case you binding source will not be updated when some property has been changed):

    BindingOperations.ClearBinding(txtContent, TextBlock.TextProperty);
    Binding binding = new Binding("Content");
    binding.Source = source;
    binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
    binding.Mode = BindingMode.OneWay;
    txtContent.SetBinding(TextBox.TextProperty, binding);
    

    When you need to resume twoway binding you can explicit update source(if you need it) than destroy oneway binding and create twoway binding.

    BindingExpression be = txtContent.GetBindingExpression(TextBox.TextProperty);
    be.UpdateSource();
    BindingOperations.ClearBinding(txtContent, TextBlock.TextProperty);
    
    Binding binding = new Binding("Content");
    binding.Source = source;
    binding.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
    binding.Mode = BindingMode.TwoWay;
    txtContent.SetBinding(TextBox.TextProperty, binding);
    

提交回复
热议问题