62

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?

Robert Höglund
  • 10,010
  • 13
  • 53
  • 70

4 Answers4

94

Alternately:

BindingOperations.ClearBinding(txtName, TextBox.TextProperty)
Ed Ball
  • 1,979
  • 2
  • 14
  • 13
  • 1
    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 Nov 11 '08 at 17:30
  • 4
    ClearBinding method does not exist in Silverlight 3. http://stackoverflow.com/questions/1639219/clear-binding-in-silverlight-remove-data-binding-from-setbinding – Aaron Hoffman Oct 28 '09 at 18:35
  • @BobKing cast it (`Nothing`) to the desired type. – ANeves Nov 24 '14 at 10:52
50

When available

BindingOperations.ClearBinding(txtName, TextBox.TextProperty)

For older SilverLight versions, but not reliable as stated in comments:

txtName.SetBinding(TextBox.TextProperty, null);

C# 6.0 features enabled

this.btnFinish.ClearBinding(ButtonBase.CommandProperty);
AZ_
  • 21,688
  • 25
  • 143
  • 191
Pop Catalin
  • 61,751
  • 23
  • 87
  • 115
19

How about:

this.ClearValue(TextBox.TextProperty);

It's much cleaner I think ;)

Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
Arcturus
  • 26,677
  • 10
  • 92
  • 107
0

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
  • 321
  • 3
  • 15