5
如何爲表單上的所有綁定調用UpdateSource?如何爲窗體上的所有綁定調用UpdateSource?
如何爲表單上的所有綁定調用UpdateSource?如何爲窗體上的所有綁定調用UpdateSource?
前段時間我爲這個任務寫了一堆幫手。
public static void UpdateAllBindingSources(this DependencyObject obj)
{
foreach (var binding in obj.GetAllBindings())
binding.UpdateSource();
}
public static IEnumerable<BindingExpression> GetAllBindings(this DependencyObject obj)
{
var stack = new Stack<DependencyObject>();
stack.Push(obj);
while (stack.Count > 0)
{
var cur = stack.Pop();
var lve = cur.GetLocalValueEnumerator();
while (lve.MoveNext())
if (BindingOperations.IsDataBound(cur, lve.Current.Property))
yield return lve.Current.Value as BindingExpression;
int count = VisualTreeHelper.GetChildrenCount(cur);
for (int i = 0; i < count; ++i)
{
var child = VisualTreeHelper.GetChild(cur, i);
if (child is FrameworkElement)
stack.Push(child);
}
}
}
然後你只需要調用從窗口
this.UpdateAllBindingSources();和你做。
不錯。但是..有什麼辦法可以在Silverlight中實現這個功能嗎? – user626528 2011-03-01 10:10:11
對,我也有興趣看到在Silverlight中有效的版本。 – Telaclavo 2012-01-07 02:16:47
對不起,我沒有找到一個簡單的方法將此解決方案移植到Silverlight。我更像是WPF開發者,所以我對SL特性的瞭解非常有限。 – 2012-03-14 08:03:50