How to do the processing and keep GUI refreshed using databinding?

前端 未结 7 641
甜味超标
甜味超标 2020-12-09 04:51

History of the problem

This is continuation of my previous question

How to start a thread to keep GUI refreshed?

but since Jon shed new light on th

7条回答
  •  死守一世寂寞
    2020-12-09 05:37

    In my WPF applications I don't send the property change directly from the model to the GUI. It always goes via a proxy (ViewModel).

    The property change events are put in a queue which is read from the GUI thread on a timer.

    Don't understand how that can be so much more work. You just need another listener for your model's propertychange event.

    Create a ViewModel class with a "Model" property which is your current datacontext. Change the databindings to "Model.Property" and add some code to hook up the events.

    It looks something like this:

    public MyModel Model { get; private set; }
    
    public MyViewModel() {
        Model = new MyModel();
        Model.PropertyChanged += (s,e) => SomethingChangedInModel(e.PropertyName);
    }
    
    private HashSet _propertyChanges = new HashSet();
    
    public void SomethingChangedInModel(string propertyName) {
        lock (_propertyChanges) {
            if (_propertyChanges.Count == 0)
                _timer.Start();
            _propertyChanges.Add(propertyName ?? "");
        }
    }
    
    // this is connected to the DispatherTimer
    private void TimerCallback(object sender, EventArgs e) {
        List changes = null;
        lock (_propertyChanges) {
            _Timer.Stop(); // doing this in callback is safe and disables timer
            if (!_propertyChanges.Contain(""))
                changes = new List(_propertyChanges);
            _propertyChanges.Clear();
        }
        if (changes == null)
            OnPropertyChange(null);
        else
            foreach (string property in changes)
                OnPropertyChanged(property);
    }
    

提交回复
热议问题