Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove binding in WPF using code

Tags:

c#

wpf

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?

like image 362
Robert Höglund Avatar asked Oct 09 '08 09:10

Robert Höglund


3 Answers

Alternately:

BindingOperations.ClearBinding(txtName, TextBox.TextProperty)
like image 51
Ed Ball Avatar answered Sep 22 '22 17:09

Ed Ball


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);
like image 36
Pop Catalin Avatar answered Sep 23 '22 17:09

Pop Catalin


How about:

this.ClearValue(TextBox.TextProperty);

It's much cleaner I think ;)

like image 34
Arcturus Avatar answered Sep 23 '22 17:09

Arcturus