Reputation: 506
I have a canvas (rectangle) where I draw a point. When I move mouse, this point changes its position, but I want to change not only position in the canvas, but also data in my model (namely 2d vector).
Can I bind position of a point on a canvas to my vector using XAML? Maybe I should create a ValueConverter, but I don't know how to get reference to canvas in the function
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture) {
...
}
Upvotes: 2
Views: 3786
Reputation: 506
Ok, finally I did the following.
I add an ellipse as a child of canvas and bind its left
and top
values to components of vector in my model. Here's XAML code:
<Canvas x:Name="MyCanvas" Background="Black" MouseMove="MyCanvas_MouseMove">
<Ellipse x:Name="PointEllipse" Canvas.Left="{Binding MyVector2D.X, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Canvas.Top="{Binding MyVector2D.Y, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" >
</Ellipse>
</Canvas>
And when I move mouse, I do the following:
private void MyCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
var pt = e.GetPosition(MyCanvas);
PointEllipse.SetValue(Canvas.LeftProperty, pt.X);
PointEllipse.SetValue(Canvas.TopProperty, pt.Y);
}
}
Upvotes: 2