Suspend Databinding of Controls

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

    You don't necessarily have to suspend binding. Another, and possibly simpler, way to do this is to suspend change notification in the view model. For instance:

    private HashSet _ChangedProperties = new HashSet();
    
    private void OnPropertyChanged(string propertyName)
    {
       if (_Suspended)
       {
          _ChangedProperties.Add(propertyName);
       }
       else
       {
          PropertyChangedEventHandler h = PropertyChanged;
          if (h != null)
          {
             h(this, new PropertyChangedEventArgs(propertyName));
          }
       }
    }
    
    private bool _Suspended;
    
    public bool Suspended
    {
       get { return _Suspended; }
       set
       {
          if (_Suspended == value)
          {
             return;
          }
          _Suspended = value;
          if (!_Suspended)
          {
             foreach (string propertyName in _ChangedProperties)
             {
                OnPropertyChanged(propertyName);
             }
             _ChangedProperties.Clear();
          }
       }
    }
    

    This will (if it's debugged and tested, which I haven't done) stop raising PropertyChanged events when Suspended is set to true, and when Suspended is set to false again it will raise the event for every property that changed while it was suspended.

    This won't stop changes to bound controls from updating the view model. I submit to you that if you're letting the user edit properties on the screen at the same time that you're changing them in the background, there's something you need to take a closer look at, and it's not binding.

提交回复
热议问题