【发布时间】:2020-05-05 04:13:56
【问题描述】:
我对 WPF 很陌生...所以我需要将线 X1 和 Y1 属性与椭圆 canvas.left 和 canvas.top 属性绑定......
在 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 是在拖动时移动它们的函数
我在这里做错了什么?
谢谢
【问题讨论】:
-
我猜你将不得不处理绑定中的
UpdateSourceTrigger。您可以通过将要绑定到的dependencyProperty 的UpdateSourceTrigger设置为OnPropertyChanged来做到这一点,然后在您的代码隐藏中实现INotifyPropertyChanged接口。 -
如果你想明确地处理更新,这里有一个链接:wpf-tutorial.com/data-binding/…
-
这里是 INotifyPropertyChange 接口的解决方案:stackoverflow.com/a/1316417/7274172
-
@Luchspeter 这与 UpdateSourceTrigger 无关,仅与 TwoWay 绑定有关。 INotifyPropertyChange 也无关紧要,因为源属性是依赖属性。
-
@Clemens 哦,好吧-感谢您的提示。但是您不应该能够将属性绑定到
Canvas.Left并像这样处理更新吗?
标签: c# wpf data-binding