【问题标题】:How to invoke UpdateSource for all bindings on the form?如何为表单上的所有绑定调用 UpdateSource?
【发布时间】:2011-03-01 14:28:58
【问题描述】:

如何为表单上的所有绑定调用 UpdateSource?

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

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

    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 中实现这一点?
    • 对,我也有兴趣看到在 Silverlight 中工作的版本。
    • 对不起,我没有找到一种简单的方法将此解决方案移植到 Silverlight。我更像是 WPF 开发人员,所以我对 SL 特性的了解非常有限。
    猜你喜欢
    • 2015-08-27
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 2011-08-16
    相关资源
    最近更新 更多