Home > Intermediate, WPF > Where is SetBinding?

Where is SetBinding?

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

Having these controls

<Slider Grid.Column=”1″ Minimum=”1″ Maximum=”5″  Grid.Row=”1″ Margin=”5″ Name=”slider2″ SmallChange=”1″ IsSnapToTickEnabled=”True” />
<TextBox Height=”23″ Margin=”5″ Grid.Row=”1″ Name=”textBox2″ VerticalAlignment=”Top” />

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

Fairly simple ha?

But what happens when the SetBinding method is simple not there?!

Take this for example:

Having the following controls

<Slider Grid.Column=”1″ Minimum=”1″  Maximum=”5″  Grid.Row=”2″ Height=”30″ VerticalAlignment=”Top” Margin=”5″ Name=”slider3″ SmallChange=”1″ />
<Rectangle Grid.Row=”2″ Height=”10″ Margin=”50″ Name=”rectangle1″ Stroke=”Black” VerticalAlignment=”Top” 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

BindingOperations.SetBinding(transform, ScaleTransform.ScaleYProperty, transformBinding);

  1. No comments yet.
  1. No trackbacks yet.