2011-03-01 45 views

回答

10

前段时间我为这个任务写了一堆帮手。

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();
和你做。

+1

不错。但是..有什么办法可以在Silverlight中实现这个功能吗? – user626528 2011-03-01 10:10:11

+0

对,我也有兴趣看到在Silverlight中有效的版本。 – Telaclavo 2012-01-07 02:16:47

+0

对不起,我没有找到一个简单的方法将此解决方案移植到Silverlight。我更像是WPF开发者,所以我对SL特性的了解非常有限。 – 2012-03-14 08:03:50

相关问题