How to clear a bind object without executing events

470 views Asked by At

I have a TextBox with a TextChanged event. This TextBox is in a StackPanel. If I make a StackPanel.Children.Clear(), the event of my TextBox is not executed.

Perfect for me!

Now, I need to bind my TextBox to the result of a database request. If I make my StackPanel.Children.Clear(), the TextChanged event IS EXECUTED!

Who know I to avoid this execution when the TextBox is Clear() ?

The solution is to Unbind my TextBox WITHOUT EVENT EXECUTION...

1

There are 1 answers

0
dovid On

clear before the binding:

BindingOperations.ClearBinding(txtName, TextBox.TextProperty)

or better

foreach (DependencyObject item in sp.Children)
    BindingOperations.ClearAllBindings(item);

sp.Children.Clear();

EDIT - For nested elements:

ClearBindings(sp);
sp.Children.Clear();

ClearBindings function:

void ClearBindings(Panel panel)
{
    foreach (DependencyObject item in panel.Children)
    {
        BindingOperations.ClearAllBindings(item);
        if (typeof(Panel).IsAssignableFrom(item.GetType()))
            ClearBindings(item as Panel);
    }
}