My app has a background thread that periodically retrieves data from an external source, in the form of key/value pairs. I would like to expose this data for binding, presumably by storing them in some kind of static(?) model, as the data will be needed by numerous views throughout my app. There are potentially hundreds of these keys, and may be different for each customer, so I can’t simply create an INotifyPropertyChanged model with a property for each value.
The app has multiple views visible at any one time, and each of these will have numerous controls (usually textboxes) that I want to bind to individual items in the above collection. When a value in the collection is updated, any controls bound to only that item should change to reflect the new value. I’m assuming an ObservableCollection wouldn’t be suitable here, as a change to a single item will result in all controls updating, regardless of which item they are bound to?
To throw a further complexity into the mix, some values (which are numeric) will need formatting for display, e.g. number of decimal places, or adding a suffix such as “volts”. The formatting rules are user-defined so I can’t hardcode them into (say) the XAML binding’s StringFormat expression. Ideally I should be able to access both the raw value (e.g. for calculations), and the formatted version (for display purposes). I’m sure it must be possible to achieve the latter using some clever WPF feature!
I would appreciate any pointers on how I can solve these requirements.
Edit: it’s worth mentioning that I’ve previously tried implementing the model as some kind of collection. The problem is that it won’t be initially populated with all values, and these only get added some time later. When they do eventually get added, a bound control doesn’t update – presumably because it wasn’t initially able to bind to the missing value.
ObservableCollectionis perfect here. You should find that a standardItemsControlbound to anObservableCollectionwill only update the controls of the items that have changed, not every item in the collection.This is the reason
ObservableCollectionexists – the events that it raises specifically identify items that have changed, so that the UI can handle them sensibly.I’ve tested this locally with a small WPF app and it works fine. Worth noting, though, that a virtualised items panel would probbaly appear to break this behaviour when it scrolls…
EDIT: rereading your question, you actually say “When a value in the collection is updated…” If your collection contains instances of a class, and you update properties on the class, you don’t even need
ObservableCollectionfor this to work – you just need the class to implementINotifyPropertyChanged.