I have problem with keeping my model (represented as List) in sync with a ListView (no databinding is used).
- Every item of the ListView corresponds to a MyObject instance in the list.
- The ListView also allows Checking/Unchecking its items corresponding to the MyObject.IsVisible property.
Current solution:
Whenever the MyObject list changes, I have a RefreshItems() method that wipes content of the ListView and regenerates its items.
I also have implemented the ItemChecked event of the ListView. Whenever the user checks/unchecks an item, I modify the corresponding MyObject.IsVisible property.
The problem is when MyObject.IsVisible is changed in the backend. The corresponding checkbox in the ListView will not get updated.
The failing fix:
Somehow, I have to cascade the status change of MyObject.IsVisible to the ListView. E.g., by calling RefreshItems(). Whenever the RefreshItems() is executed, the ListView.ItemChanged events are automatically invoked. This results an infinit loop and stackoverflow exception.
- RefreshItems() => updates ListView based on the model
- ListView is changed, hence the ItemChecked is invoked as many times as many items we have
- ItemChecked updates the model based on the ListView
- the model change causes the cicle starting again. GOTO 1
Inside the ItemChanged eventhandler, I have no means to detect who initiated the change (i.e., the user by clicking or the RefreshItems method by populating the items), so gives me no option to break out of the infinit loop.
How can I solve this?
I will try, before the call to RefreshItems(), to detach the event handler for ItemChanged.
And reattach afterward.