在显示浮动线时跟踪鼠标单击

时间:2019-01-24 20:55:03

标签: c# wpf line

试图找到一种表达方式。.因此,我的代码在双击时在航海图上放置了一个航点。放置第一个航点后,我想在航点和鼠标光标位置之间创建一条线。这似乎可行,但是在绘制线条之后,我将不再能够与地图进行交互或放置任何其他航路点。双击事件未触发,因为线程似乎不断在mouse_move上重画线,这是StackPanel上的事件。

public async void _navigationChartPanel_MouseMove(object sender, MouseEventArgs e)
{
    foreach (var element in _panelChart.Children)
    {
        if (element is Line && ((Line)element).Name == "RangeBearingLine")
        {
            index = _panelChart.Children.IndexOf(element);
            break;
        }
    }

    if (index >= 0)
    {
        _panelChart.Children.RemoveAt(index);
    }

    var line = new Line
    {
        Name = "RangeBearingLine",
        StrokeThickness = 1,
        Stroke = System.Windows.Media.Brushes.Red,
        X1 = _parent._routePlanner.lastWaypointLoc.X,
        Y1 = _parent._routePlanner.lastWaypointLoc.Y,
        X2 = mouseClick.X,
        Y2 = mouseClick.Y
    };

    _panelChart.Children.Add(line); 

据我了解,我需要在控件下方显示仍可见的行,但并不妨碍我与UI进行交互。我不是WPF的专家,但是除了一遍又一遍地触发MouseMove事件之外,我想不出另一种方式来显示跟随鼠标的行。有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是将您创建的子元素的IsHitTesting设置为false。一种更简单的方法是拦截PreviewMouseDown,因为这是一个隧道事件,因此将在子控件之前调用父控件:

<Canvas x:Name="theCanvas" Background="CornflowerBlue" PreviewMouseDown="Canvas_MouseDown" PreviewMouseMove="Canvas_MouseMove">
    <Rectangle Canvas.Left="100" Canvas.Top="100" Width="200" Height="200" Fill="Green" /> <!-- to show that it will also work when you click on other children -->
</Canvas>

然后在主窗口类中:

public partial class MainWindow : Window
{
    private Line CurrentLine;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
    {           
        var pos = e.GetPosition(theCanvas);
        if (e.ClickCount == 2)
        {
            this.CurrentLine = new Line
            {
                Name = "RangeBearingLine",
                StrokeThickness = 1,
                Stroke = System.Windows.Media.Brushes.Red,
                X1 = pos.X,
                Y1 = pos.Y,
                X2 = pos.X,
                Y2 = pos.Y
            };
            theCanvas.Children.Add(this.CurrentLine);
            e.Handled = true;
        }
        else if ((e.ClickCount == 1) && (this.CurrentLine != null))
        {
            this.CurrentLine.X2 = pos.X;
            this.CurrentLine.Y2 = pos.Y;
            this.CurrentLine = null;
            e.Handled = true;
        }
    }
    private void Canvas_MouseMove(object sender, MouseEventArgs e)
    {
        if (this.CurrentLine == null)
            return;
        var pos = e.GetPosition(theCanvas);
        this.CurrentLine.X2 = pos.X;
        this.CurrentLine.Y2 = pos.Y;
        e.Handled = true;
    }

}