我有两个按钮,需要用线连接它们。 我将线坐标绑定到按钮位置。
我需要通过代码添加此绑定。
在XAML中,这项工作非常好:
<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)}"/>
现在,在代码中,我尝试了:
Binding b = new Binding("(Canvas.Left)");
b.ElementName = "button1";
testLine.SetBinding(System.Windows.Shapes.Line.X1Property, "(Canvas.Left)");
但这不起作用......(
编辑:
动态创建元素时存在一个问题:
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);
似乎“be1”不存在或者我不知道是什么......
button1.RegisterName(button1.Name, button1); //does not help, error...
答案 0 :(得分:2)
你确定你不是故意的:
Binding b = new Binding("(Canvas.Left)");
b.ElementName = "button1";
testLine.SetBinding(System.Windows.Shapes.Line.X1Property, b);
编辑:
根本不需要元素名称:
Button button1 = new Button();
Canvas.SetLeft(button1, 50);
Canvas.SetTop(button1, 50);
mainCanvas.Children.Add(button1);
Button button2 = new Button();
Canvas.SetLeft(button2, 150);
Canvas.SetTop(button2, 150);
mainCanvas.Children.Add(button2);
//juse Source reference not ElementName
Binding b1 = new Binding() { Source = button1, Path = new PropertyPath("(Canvas.Left)") };
Binding b2 = new Binding() { Source = button2, Path = new PropertyPath("(Canvas.Left)") };
testLine.SetBinding(System.Windows.Shapes.Line.X1Property, b1);
testLine.SetBinding(System.Windows.Shapes.Line.X2Property, b2);
答案 1 :(得分:1)
可能只是打字错误。您创建绑定但不使用它。尝试:
testLine.SetBinding(System.Windows.Shapes.Line.X1Property, b);
答案 2 :(得分:1)
尝试使用SetBinding的其他重载...您在代码中创建了一个新绑定,但实际上并没有使用它。
Binding b = new Binding("(Canvas.Left)");
b.ElementName = "button1";
testLine.SetBinding(System.Windows.Shapes.Line.X1Property, b);