How to set binding to ScaleTransform ScaleX in C # code (not XAML)?

I am trying to snap some graphics to a slider to adjust the graphic size in the code. I tried different ways, but cannot find a way to bind the ScaleTransform ScaleX property in C # code. (I generate this in temporary code, so there is no XAML)

Here is my sample code that 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);
+3
source share
1 answer

First, you need to specify ScaleTransformand Slidername in XAML

In this case, the button

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

Then you create Bindingand use BindingOperations.SetBindingtoegether to connect to things.

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 a slider in the code, you use .Sourceinstead.ElementName

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

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

Source: https://habr.com/ru/post/1795208/


All Articles