我尝试在图像上添加一条线。到目前为止,当我在一个新项目中添加一行时,它只使用网格和图像。
另一方面,当我在另一个项目中使用相同的代码时,添加的行是 not ,其中我也使用网格和带有其他元素的图像。我想该行已添加但是从图像本身隐藏或在另一个控件,网格或边框后面隐藏。所以我的问题是,如何将我的行作为最顶层放在图像前面?
grid2.Children.Add(myLine);
大纲如下所示: 窗口 - >的 GRID1 - >的边界 - >的 GRID2 - > 图片 (在此图片上我想添加一行)
线元素:
// Add a Line Element
static Line myLine = new Line
{
Stroke = Brushes.GreenYellow,
StrokeThickness = 2,
Visibility = Visibility.Visible
};
在这里,我读了这一行的两个要点:
private void image_zoom0_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
if (_firstPoint)
{
grid2.Children.Remove(myLine); // remove line first
System.Windows.Point position = Mouse.GetPosition(image_zoom0);
myLine.X1 = position.X;
myLine.Y1 = position.Y;
_firstPoint = false;
}
else
{
System.Windows.Point position = Mouse.GetPosition(image_zoom0);
myLine.X2 = position.X;
myLine.Y2 = position.Y;
_firstPoint = true;
grid2.Children.Add(myLine); // draw line
Canvas.SetZIndex(myLine,99);
}
}
}
答案 0 :(得分:1)
我不确定您对此代码的期望是什么。但是,我创建了一个示例wpf应用程序并按原样复制了image_zoom0_MouseLeftButtonDown方法。
注意 -
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" WindowState="Maximized">
<Grid x:Name="grid1">
<Border>
<Grid x:Name="grid2">
<Image x:Name="image_zoom0" Source="Background3.jpg" MouseLeftButtonDown="image_zoom0_MouseLeftButtonDown" Stretch="UniformToFill"/>
</Grid>
</Border>
</Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
static Line myLine = new Line
{
Stroke = Brushes.GreenYellow,
StrokeThickness = 2,
Visibility = Visibility.Visible
};
bool _firstPoint;
private void image_zoom0_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
if (_firstPoint)
{
grid2.Children.Remove(myLine); // remove line first
System.Windows.Point position = Mouse.GetPosition(image_zoom0);
myLine.X1 = position.X;
myLine.Y1 = position.Y;
_firstPoint = false;
}
else
{
System.Windows.Point position = Mouse.GetPosition(image_zoom0);
myLine.X2 = position.X;
myLine.Y2 = position.Y;
_firstPoint = true;
grid2.Children.Add(myLine); // draw line
//Canvas.SetZIndex(myLine, 99);
}
}
}
}
现在根据MouseLeftButtonDown中写的逻辑,当你第一次点击图像时,一条线从窗口的TopLeft绘制到当前的鼠标位置。 第二次点击只会删除该行。第三次单击将再次从先前鼠标位置绘制线到当前鼠标位置,第四次单击将再次将其删除,依此类推。