tags:

views:

3755

answers:

4

I would like to use databinding when displaying data in a TextBox. I'm basically doing like:

 public void ShowRandomObject(IRandomObject randomObject) {
        Binding binding = new Binding {Source = randomObject, Path = new PropertyPath("Name")};
        txtName.SetBinding(TextBox.TextProperty, binding);
    }

I can't seem to find a way to unset the binding. I will be calling this method with a lot of different objects but the TextBox will remain the same. Is there a way to remove the previous binding or is this done automatically when I set the new binding?

A: 

Isn't this working?

txtName.SetBinding(TextBox.TextProperty, null);

P.S. The previous binding is removed when you call set binding again, and becomes garbage for GC to collect.

Pop Catalin
I suspected that the previous binding was removed when setting a new since I couldn't find any information on how to do it. Thanks!
Robert Höglund
This doesn't work. SetBinding is overloaded and the call becomes ambiguous when null is provided as the second parameter
Simon Fox
@Simon, when the call is ambiguous you can always cast the null value to the desired type to solve the ambiguity ;) IE: (Binding)null
Pop Catalin
@Pop, your right that would work however Eds approach below is provided by the framework so obviously preferable
Simon Fox
@Simon, I agree!
Pop Catalin
+4  A: 

How about:

this.ClearValue(TextBox.TextProperty);

Its much cleaner I think ;)

Arcturus
The documentation on this method is not very clear. It reads as if it will just clear the Value, Not the Binding. But in practice, this appears to be working.
Aaron Hoffman
BindingOperations.ClearBinding() calls this method internally.
Aaron Hoffman
+23  A: 

Alternately:

BindingOperations.ClearBinding(txtName, TextBox.TextProperty)
Ed Ball
Visual Basic won't resolve the .SetBinding(..., Nothing) call because both signatures take Reference types (a String, and a BindingBase). I like this better.
Bob King
ClearBinding method does not exist in Silverlight 3. http://stackoverflow.com/questions/1639219/clear-binding-in-silverlight-remove-data-binding-from-setbinding
Aaron Hoffman
A: 

How about just

txtName.Text = txtName.Text;

You would have to set the value after clearing it anyways. This works in SL4 at least.

Bodekaer