WPF词典绑定失败是很慢 [英] WPF Dictionary Binding failure is very slow
问题描述
我有大部分的标签在我的应用程序
对象的约束,这样它们可以从Web服务所取代。
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.
下面是一个例子:(正确地注意这个code函数,它仅仅是缓慢的,如果它不能找到匹配)的
<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?
推荐答案
如果你有选择,我会改变你的的IDictionary
实施一个返回空
,而使用 TargetNullValue
(或者甚至是的IDictionary&LT; TKEY的,对象&gt;
并返回 DependencyProperty.UnsetValue
如果你还在用 FallbackValue
):
If you have the option to, I would change your IDictionary
implementation to one that returns null
and instead use TargetNullValue
(or even be IDictionary<TKey, object>
and return DependencyProperty.UnsetValue
if you still use 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
}
}
这篇关于WPF词典绑定失败是很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!