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

时间:2011-03-01 05:50:52

标签: c# .net wpf

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

1 个答案:

答案 0 :(得分:12)

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

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();
就可以了。