I have most of the Label objects in my app bound such that they can be replaced from a webservice.
I store my replacements in a Dictionary. The replacements vary based on the Client that loaded for the app.
The problem I am having is that most of the time I don’t replace the labels, and the binding failure is throwing an exception that is very slow.
Here is an example: (Note this code functions correctly, it is just slow if it can’t find a match.)
<Label Content="_Gender"
Helpers:CaptionHelper.PropertyName="Content"
Helpers:CaptionHelper.PropertyValue="{Binding Labels[Gender],
FallbackValue=_Gender}"
Target="{Binding ElementName=cbGender}" />
When the binding tries to lookup Lables[Gender], I get this in my output window:
System.Windows.Data Warning: 17 : Cannot get 'Item[]' value (type 'String') from 'Labels' (type 'Dictionary`2'). BindingExpression:Path=Labels[Gender]; DataItem='MyViewMV'
(HashCode=63776763); target element is 'Label' (Name=''); target property is 'PropertyValue'(type 'String') TargetInvocationException:'System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. ---> System.Collections.Generic.KeyNotFoundException:
The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Params Truncated)
at System.Reflection.RuntimeMethodInfo.Invoke(Params Truncated)
at System.Reflection.RuntimeMethodInfo.Invoke(Params Truncated)
at MS.Internal.Data.PropertyPathWorker.GetValue(Params Truncated)
at MS.Internal.Data.PropertyPathWorker.RawValue(Params Truncated)'
Since I have a lot of these, it is taking about a full second to run through them all.
Is there a way to make the binding not throw an exception when the dictionary look up fails? Or somehow fail quicker?
If you have the option to, I would change your
IDictionaryimplementation to one that returnsnulland instead useTargetNullValue(or even beIDictionary<TKey, object>and returnDependencyProperty.UnsetValueif you still useFallbackValue):