I want to draw a line on a WPF Grid.
private void InitializeTestline()
{
testline = new Line();
grid.Children.Add(testline);
testline.X1 = 0;
tes
I was doing this same basic thing only on a maze, and this is what i would do
private void Move_Up Click(object sender, RoutedEventArgs e)
{
Point testlinelocation;
testlinelocation = testline.Y1;
testlinelocation.Offset(someX, someY);
testlinelocation = testline.Y1;
}
This should work, it worked for me, best of luck This is in winforms
Firstly, I would not manipulate coordinates as their are primarily for defining shape of the line. Secondly, I wouldn't use Canvas, but Render Transformation instead, as it potentially runs on GPU instead of CPU which makes animation smoother.
So I would do something like this:
XAML:
<Grid x:Name="LayoutRoot">
<Line x:Name="crosshair"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Stroke="Red"
X1="0"
X2="0"
Y1="10"
Y2="0" />
<Button Width="50"
Height="50"
HorizontalAlignment="Right"
Click="MoveRight"
Content=">" />
</Grid>
Code Behind:
public partial class MainWindow : Window
{
private int moveRightDist = 0;
public MainWindow()
{
InitializeComponent();
}
private void MoveRight(object sender, RoutedEventArgs e)
{
this.moveRightDist++;
crosshair.RenderTransform = new TranslateTransform(this.moveRightDist, 0);
}
}
<Grid x:Name="LayoutRoot">
<Line x:Name="crosshair"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Stroke="Red"
X1="0"
X2="0"
Y1="10"
Y2="0" />
<Button Width="50"
Height="50"
HorizontalAlignment="Right"
Click="MoveRight"
Content=">" />
</Grid>
Important! If you define Affine transformation matrix in XAML and animate it, at some point WPF will substitute the instance of that matrix and if you are refering to that matrix in your code you might not be able to manipulate an object.
Side Note: I would rather create all UI elements in XAML (Blend is a great tool for that) and then would use refer to them from code behind.