【问题标题】:Set UI Element Position to Mouse Position将 UI 元素位置设置为鼠标位置
【发布时间】:2015-09-17 12:30:00
【问题描述】:

我写了一个小程序,它应该在鼠标的确切位置显示一个椭圆。问题是,我现在这样做的方式,鼠标和椭圆位置只在屏幕的中心。如果我把鼠标放在离窗口边框更远的地方,它们会越来越远。

我使用 MouseOver 元素来更新鼠标位置。

这是我的代码:

         private void Window_MouseMove(object sender, MouseEventArgs e)
       {
        Main_Grid.Children.Clear();

        MousePos_Ellipse = new Ellipse();
        Point MousePos_Point = new Point();

        MousePos_Point = Mouse.GetPosition(Main_Grid);

        Main_Grid.Children.Remove(MousePos_Ellipse);

        SolidColorBrush mySolidColorBrush = new SolidColorBrush();


        mySolidColorBrush.Color = Color.FromArgb(55, 255, 255, 0);
        MousePos_Ellipse.Fill = mySolidColorBrush;
        MousePos_Ellipse.StrokeThickness = 2;
        MousePos_Ellipse.Stroke = Brushes.Black;

        // Set the width and height of the Ellipse.
        MousePos_Ellipse.Width = 15;
        MousePos_Ellipse.Height = 15;
        // At this Point I do my Positioning
        MousePos_Ellipse.Margin = new Thickness(left: MousePos_Point.X - ( Main_Grid.ActualWidth / 2)  , top: MousePos_Point.Y - ( Main_Grid.ActualHeight / 2 ), right: 0 , bottom: 0);

        //base.AddVisualChild(_circle);

        // Add the Ellipse to the Grid
        Main_Grid.Children.Add(MousePos_Ellipse);

    }

【问题讨论】:

  • 使用画布而不是网格
  • 画布控件是您要用于显式定位子元素的控件。您将在其他实现特定布局样式的控件中遇到问题。

标签: c# wpf


【解决方案1】:

我建议使用Canvas 而不是网格。

使用画布,您可以像这样简单地设置椭圆位置:

   Canvas.SetLeft(MousePos_Ellipse, MousePos_Point.X);
   Canvas.SetTop(MousePos_Ellipse, MousePos_Point.Y);

Grid 控件会自动定位和调整子元素的大小,因此不太适合您的目标。

【讨论】:

【解决方案2】:

免责声明;虽然上面的答案可以解决您的问题,但实际问题并未得到妥善解决。您面临的问题源于您对问题的解释与计算机如何看待它相比。

光标相对于网格的位置与相对于屏幕的位置不同(即不同的分辨率返回不同的值)。这就是为什么我们的 x 和 y 值越偏离中心越远。您可以通过定义您希望您的 X 和 Y 位置相对于表单、f.ex 来解决此问题,如下所示:

    var relativePoint = this.PointToClient(Cursor.Position);

这里的显着区别是,这里我们指向客户端,因此获得了光标在表单中的相对位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多