Posted 31 Oct 2012
Link to this post
I have a scenario in which I have a ViewModel of a particular type that can hold a Model that can be one of a set of types.
The ViewModel inherits from DynamicObject to expose elements within the Model as properties for the PropertyGrid. In my DynamicObject implementation I am overriding GetDynamicMemberNames, TryGetMember, and TrySetMember. I am keeping my own dictionary of member names and accessors within my ViewModel.
The underlying Model may have different members so that each instance of the ViewModel should appear to have different properties.
I have a list of instances of the ViewModel and the PropertyGrid is bound to the list's selected item. When I switch items, WPF databinding makes calls to TryGetMember within the newly selected ViewModel. However, when that set of calls are made, they're based on the member names returned by the previous instance.
So let's say I have Model1 with properties A, B, C and Model 2 with properties D, E, F. Instances of either can be held in an instance of my dynamic ViewModel. I add an instance of each to the list. I select the item containing the instance of Model1, the PropertyGrid shows three properties A, B, C just fine. When I select the item containing Model2 however, I get an error within my TryGetMember saying that the key isn't found, I look at the binder.Name and it's reading "A" even though this new instance of ViewModel has a model of type Model2 with only the properties D, E, F.
When I switch between these two items, GetDynamicMemberNames() isn't called more than once. I suspect that somewhere along the way the member names are being cached by the name of the type they're associated with. So in this internal cache someplace it's associating my ViewModel class with properties A, B, C and uses that cache to query all instances of ViewModel.
My questions are:
1) Do you know where this caching is happening? Is this in PropertyGrid, in WPF databinding, or within the DynamicObject base class?
2) Is there any way to override the member name caching?
3) Is there any way to force a call to GetDynamicMemberNames() each time a new instance of my ViewModel is loaded into the PropertyGrid?
Thanks for your help.