KMC
KMC

Reputation: 20046

How to SetBinding to ScaleTransform's ScaleX in C# code (not XAML)?

I am trying to databind some graphics to a slider to adjust the graphic size in code-behind. I tried various ways but I can't find a way to bind the the ScaleTransform's ScaleX property in C# code. (I'm generating this in run-time code, so no XAML)

Here is my sample code, which doesn't work

Line lR = new Line();
lR.X1 = 0;
lR.Y1 = 0;
lR.X2 = 150;
lR.Y2 = 150;
lR.Stroke = new SolidColorBrush(Colors.Blue);
lR.StrokeThickness = 2;

ScaleTransform lRSt = new ScaleTransform();
lR.RenderTransform = lRSt;

Slider sliderR = new Slider();
sliderR.Minimum = 1;
sliderR.Maximum = 3;
sliderR.Value = 1;
sliderR.TickPlacement = TickPlacement.BottomRight;
sliderR.TickFrequency = 0.2;
sliderR.IsSnapToTickEnabled = true;

/* Set Binding between Slider and Canvas Children */
Binding sliderRBind1 = new Binding();
sliderRBind1.Source = sliderRBind1;
sliderRBind1.Path = new PropertyPath("Value");
BindingOperations.SetBinding(lRSt, ScaleTransform.ScaleXProperty, sliderRBind1);

Upvotes: 3

Views: 3542

Answers (1)

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

First you need to give the ScaleTransform and the Slider a name in the XAML

In this case a Button

<Button.RenderTransform>
    <ScaleTransform x:Name="btnScaleTransform" />
</Button.RenderTransform>

Then you create a Binding and use BindingOperations.SetBinding to wire things toegether.

var aBinding = new Binding();
aBinding.ElementName = "slider1"; // name of the slider
aBinding.Path = new PropertyPath("Value");

BindingOperations.SetBinding(
    btnScaleTransform, // the ScaleTransform to bind to
    ScaleTransform.ScaleXProperty,
    aBinding);            

Edit:
If you want to declare the slider in code too you use .Source instead of .ElementName

var slider1 = new Slider();
grid1.Children.Add(slider1);

var aBinding = new Binding();
aBinding.Source = slider1;
aBinding.Path = new PropertyPath("Value");

Upvotes: 6

Related Questions