Where is SetBinding?

While you’re programmatically creating binding in WPF you’ve probably used objectName.SetBinding quite a lot.

Having these controls


<TextBox Name="textBox2">

you can create a binding between the slider2’s Value and the textBox2’s  Text with the following code:

Binding sliderTextBoxBinding = new Binding();
sliderTextBoxBinding.Source = slider2;
sliderTextBoxBinding.Path = new PropertyPath("Value");
textBox2.SetBinding(TextBox.TextProperty, sliderTextBoxBinding);

What happens when the SetBinding method is simple not there?!

Take this for example:

Having the following controls

<Rectangle Name="rectangle1" 
Fill="Gray" >

let’s say you want to bind the rectangle1‘s ScaleY property of a ScaleTransform applied as a RenderTransform to the slider3‘s Value

First of all, you can’t directly bind the two together.

You have to create a ScaleTransform and assign it to the rectangle1‘s RenderTransform

ScaleTransform transform = new ScaleTransform();
rectangle1.RenderTransform = transform;

When you modify the transform object the changes will automatically propagate to rectangle1 and you will notice the changes.

Now let’s bind this transform to the slider3 Value.

Binding transformBinding = new Binding();
transformBinding.Source = slider3;
transformBinding.Path = new PropertyPath("Value");

transform.SetBinding(ScaleTransform.ScaleYProperty, transformBinding);

But wait! transform has no SetBinding method

Well, in this case, use BindingOperations.SetBinding

“BindingOperations.SetBinding creates and associates a new instance of  BindingExpressionBase with the specified binding target property”. You can find more details here.

So our code now becomes


Happy coding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.