Pip*_*ppl 7 c# wpf drawing move line
我想在WPF网格上画一条线.
private void InitializeTestline()
{
testline = new Line();
grid.Children.Add(testline);
testline.X1 = 0;
testline.X2 = 1;
testline.Y1 = 0;
testline.Y2 = 1;
testline.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
testline.VerticalAlignment = System.Windows.VerticalAlignment.Top;
testline.Stroke = Brushes.Red;
testline.Stretch = Stretch.Fill;
testline.StrokeThickness = 2;
testline.Visibility = System.Windows.Visibility.Visible;
}
Run Code Online (Sandbox Code Playgroud)
它没有问题.但现在我想在网格上添加四个按钮(向上,向下,向左,向右).因此,当我按下其中一个按钮时,线条应朝我选择的方向移动.
private void MoveUp_Click(object sender, RoutedEventArgs e)
{
this.testline.Y1 += move;
this.testline.Y2 += move;
}
Run Code Online (Sandbox Code Playgroud)
这是我想要使用的功能,但它不起作用.那么如何移动这条线呢?
最后,我有一个古老的终端3270 gui,这些gui有一个插入符号.这些线应该像一个十字准线(并帮助看看插入符的实际位置)
首先,我不会操纵坐标,因为它们主要用于定义线的形状。其次,我不会使用 Canvas,而是使用 Render Transformation,因为它可能在 GPU 而不是 CPU 上运行,这使得动画更流畅。
所以我会做这样的事情:
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>
Run Code Online (Sandbox Code Playgroud)
背后代码:
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>
Run Code Online (Sandbox Code Playgroud)
重要的!如果您在 XAML 中定义仿射变换矩阵并对其进行动画处理,则在某些时候 WPF 将替换该矩阵的实例,并且如果您在代码中引用该矩阵,您可能无法操作对象。
旁注:我宁愿在 XAML 中创建所有 UI 元素(Blend 是一个很棒的工具),然后从后面的代码中引用它们。