WPF : How to refresh model data values only when binding is active?
I'm working on a application which is communicating by network to monitor another application's variables.
The remote application has loads of variables, and I want开发者_Go百科 to transfer only the variables that I'm currently watching on my user interface, to avoid overloading the network.
I try to keep the architecture of my application as clean as possible, with a model that doesn't know about the view, using bindings, etc.
I thought about refreshing my model data values only when the bindings are active (which mean that the usercontrol displaying some of the variables is shown), do you think it's a good solution? Otherwise, I could also work with the property "IsVisible" of each usercontrol... but I think it would be better to work on the model side of my application I think.
Do you know if there is a way to know if a binding is active or not?
If my question isn't clear enough, I could draw a small schema. Just tell me.
Remember that binding is only refreshed when a change is posted via INotifyPropertyChanged (or in the case of a two-way binding your UI modifies a two-way binded variable). Most of the time, you will explicitly query a service. When the service response comes back, you will modify properties in your ViewModel and call the PropertyChanged event to tell the bindings to update themselves.
Essentially, your binding isn't going to update unless you tell it to. ObservableCollections will automatically update the binding because they internally implement INotifyPropertyChanged. But still, that only happens when you update the collection.
To answer your question, yes, keep network chatter down by only updating when you absolutely need to. Since you are using WPF and INotifyPropertyChanged, this will only happen when you invoke an update to a bound variable + fire the event.
If a binding is "active" (I assume you mean that there are dependency properties interested in the property) they will call the getter for the property on notifypropertychanged for the particular property.
So, as long as you're not firing NotifyPropertyChanged superfluously, every time the get of your property is being called, you are safe to do whatever data refreshing applies to that property.
This SO question and answers inspired me to create markup extension named VisibleBinding when using it - the binding will be applied (therefore will listen to INotifyPropertyChanged on source) only when control is visible.
Check my blog post for more details.
精彩评论