有没有办法获取窗口的所有 BindingExpression 对象?
当需要触发刷新表单的 PropertyChanged 事件数量太高且不是一个好的选择时,我尝试刷新表单。我正在考虑以另一种方式进行操作,即表单/窗口可以重新查询所有绑定。
如果你加注PropertyChanged
与PropertyChangedEventArgs
其参数为null
or String.Empty
所有属性的绑定都将更新。
[MSDN 参考 http://msdn.microsoft.com/en-us/library/system.componentmodel.propertychangedeventargs.propertyname.aspx]
我认为相反的做法要复杂得多,而且可能会消耗更多的性能。您需要检查整个窗口中每个 DependencyObject 的每个 DependencyProperty 是否有绑定。
Edit:编写了以下粗略的扩展方法,它可以满足您的要求,效率非常低(可能还有改进的空间,但您仍在处理相当复杂的算法):
public static void UpdateAllBindings(this DependencyObject o)
{
//Immediate Properties
List<FieldInfo> propertiesAll = new List<FieldInfo>();
Type currentLevel = o.GetType();
while (currentLevel != typeof(object))
{
propertiesAll.AddRange(currentLevel.GetFields());
currentLevel = currentLevel.BaseType;
}
var propertiesDp = propertiesAll.Where(x => x.FieldType == typeof(DependencyProperty));
foreach (var property in propertiesDp)
{
BindingExpression ex = BindingOperations.GetBindingExpression(o, property.GetValue(o) as DependencyProperty);
if (ex != null)
{
ex.UpdateTarget();
}
}
//Children
int childrenCount = VisualTreeHelper.GetChildrenCount(o);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(o, i);
child.UpdateAllBindings();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)