I have two buttons, and need to link them with a line. I bind the Line coordinates to the button positions.
I need to add this binding by code.
In XAML this work very well like this:
<Button x:Name="button1" Width="10" Height="10" Canvas.Left="150" Canvas.Top="150"/>
<Button x:Name="button2" Width="10" Height="10" Canvas.Left="250" Canvas.Top="100"/>
<Line x:Name="testLine" Stroke="Black"
X1="{Binding ElementName=button1, Path=(Canvas.Left)}"
Y1="{Binding ElementName=button1, Path=(Canvas.Top)}"
X2="{Binding ElementName=button2, Path=(Canvas.Left)}"
Y2="{Binding ElementName=button2, Path=(Canvas.Top)}"/>
Now, in code, I tried:
Binding b = new Binding("(Canvas.Left)");
b.ElementName = "button1";
testLine.SetBinding(System.Windows.Shapes.Line.X1Property, "(Canvas.Left)");
but this does not work... (
EDIT :
There is one problem when creating dynamically the element:
Button button1 = new Button();
Canvas.SetLeft(button1, 50);
Canvas.SetTop(button1, 50);
button1.Name = "be1";
mainCanvas.Children.Add(button1);
Button button2 = new Button();
Canvas.SetLeft(button2, 150);
Canvas.SetTop(button2, 150);
button2.Name = "be2";
mainCanvas.Children.Add(button2);
Binding b1 = new Binding() { ElementName = "be1", Path = new PropertyPath("(Canvas.Left)") };
Binding b2 = new Binding() { ElementName = "be2", Path = new PropertyPath("(Canvas.Left)") };
testLine.SetBinding(System.Windows.Shapes.Line.X1Property, b1);
testLine.SetBinding(System.Windows.Shapes.Line.X2Property, b2);
It seems that "be1" does not exist or I don't know what...
button1.RegisterName(button1.Name, button1); //does not help, error...