我有大部分Label
我的应用程序中的对象已绑定,以便可以从网络服务中替换它们。
我将替换内容存储在字典中。替换内容根据为应用程序加载的客户端而有所不同。
我遇到的问题是,大多数时候我不替换标签,并且绑定失败会引发非常慢的异常。
这是一个例子:(请注意,此代码可以正常运行,如果找不到匹配项,则速度会很慢。)
<Label Content="_Gender"
Helpers:CaptionHelper.PropertyName="Content"
Helpers:CaptionHelper.PropertyValue="{Binding Labels[Gender],
FallbackValue=_Gender}"
Target="{Binding ElementName=cbGender}" />
当绑定尝试查找 Lables[Gender] 时,我会在输出窗口中看到以下内容:
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)'
由于我有很多这样的内容,所以大约需要一秒钟的时间才能浏览完所有这些内容。
有没有办法让绑定在字典查找失败时不抛出异常?或者以某种方式更快地失败?
如果你可以选择的话,我会改变你的IDictionary
实现返回null
并改为使用TargetNullValue
(或者甚至是IDictionary<TKey, object>
并返回DependencyProperty.UnsetValue
如果你还在使用FallbackValue
):
public class PassthruDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private Dictionary<TKey, TValue> instance;
// ... other stuff
public TValue this[TKey key]
{
get
{
TValue value;
if (instance.TryGetValue(key, out value))
{
return value;
}
else
{
return default(TValue);
}
}
// ... more
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)