Remove binding in WPF using code

C#Wpf

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Alternately:

BindingOperations.ClearBinding(txtName, TextBox.TextProperty)

Solution 2 - C#

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

Solution 3 - C#

How about:

this.ClearValue(TextBox.TextProperty);

It's much cleaner I think ;)

Solution 4 - C#

How about just

txtName.Text = txtName.Text;

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobert HöglundView Question on Stackoverflow
Solution 1 - C#Ed BallView Answer on Stackoverflow
Solution 2 - C#Pop CatalinView Answer on Stackoverflow
Solution 3 - C#ArcturusView Answer on Stackoverflow
Solution 4 - C#BodekaerView Answer on Stackoverflow