Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke UpdateSource for all bindings on the form?

Tags:

c#

.net

wpf

How to invoke UpdateSource for all bindings on the form?

like image 483
user626528 Avatar asked Mar 01 '11 05:03

user626528


1 Answers

Some time ago I wrote a bunch of helpers for this task.

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);
        }
    }
}

Then you just call

this.UpdateAllBindingSources();
from your window and you are done.
like image 75
Oleg Tarasov Avatar answered Sep 21 '22 22:09

Oleg Tarasov