如何在代码隐藏WPF中绑定属性



我对WPF很陌生。。。所以我需要用一个省略号canvas.left和canvas.top来绑定一个行X1和Y1的属性。。。。。。

在XAML中,它运行良好。。。

XAML代码

<Ellipse x:Name="tst" Width="40" Height="40" Canvas.Left="150" Canvas.Top="150" Stroke="Blue" StrokeThickness="2" MouseMove="adjustRoute"/>
<Line X1="{Binding ElementName=tst, Path=(Canvas.Left)}" Y1="{Binding ElementName=tst, Path=(Canvas.Top)}" X2="300" Y2="200" Stroke="Blue" StrokeThickness="2"/>

但我需要在使用C#的代码背后做这件事

所以我做了这个

temp = new Line();
tempe = new Ellipse();
tempe.Fill = Brushes.Transparent;
tempe.Stroke = Brushes.Blue;
tempe.StrokeThickness = 1;
tempe.Width = 20;
tempe.Height = 20;
Canvas.SetLeft(tempe, currentPoint.X-10);
Canvas.SetTop(tempe, currentPoint.Y-10);
tempe.MouseMove += adjustRoute;
Binding binding = new Binding { Source = tempe, Path = new PropertyPath(Canvas.LeftProperty), UpdateSourceTrigger=UpdateSourceTrigger.PropertyChanged };
temp.SetBinding(Line.X1Property, binding);
Binding binding2 = new Binding { Source = tempe, Path = new PropertyPath(Canvas.TopProperty), UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
temp.SetBinding(Line.Y1Property, binding2);
temp.Stroke = Brushes.Blue;
temp.StrokeThickness = 2;
temp.X1 = currentPoint.X;
temp.Y1 = currentPoint.Y;
temp.X2 = currentPoint.X + 200;
temp.Y2 = currentPoint.Y + 200;
testcanv.Children.Add(temp);
testcanv.Children.Add(tempe);

但当我移动椭圆时,它不会更新线的位置(在XAML中它会更新(。。。。

这里currentPoint是我在运行时用鼠标点击来绘制形状的点,adjustRoute是在拖动时移动它们的功能

我在这里做错了什么?

感谢

确保只创建一次Line和Ellipse元素,只分配一次Bindings。将鼠标移动处理程序指定给Canvas而不是Ellipse:

private Line line;
private Ellipse ellipse;
public MainWindow()
{
InitializeComponent();
line = new Line
{
Stroke = Brushes.Blue,
StrokeThickness = 2
};
ellipse = new Ellipse
{
Stroke = Brushes.Blue,
StrokeThickness = 1,
Width = 20,
Height = 20,
Margin = new Thickness(-10)
};
Binding xBinding = new Binding
{
Source = ellipse,
Path = new PropertyPath(Canvas.LeftProperty)
};
line.SetBinding(Line.X1Property, xBinding);
Binding yBinding = new Binding
{
Source = ellipse,
Path = new PropertyPath(Canvas.TopProperty)
};
line.SetBinding(Line.Y1Property, yBinding);
testcanv.Children.Add(line);
testcanv.Children.Add(ellipse);
testcanv.Background = Brushes.Transparent;
testcanv.MouseMove += adjustRoute;
}
private void adjustRoute(object sender, MouseEventArgs e)
{
var p = e.GetPosition(testcanv);
Canvas.SetLeft(ellipse, p.X);
Canvas.SetTop(ellipse, p.Y);
}

相关内容

  • 没有找到相关文章

最新更新