【问题标题】:Detect mousedown event on canvas elements检测画布元素上的 mousedown 事件
【发布时间】:2013-06-16 18:18:40
【问题描述】:

好吧,因为除了熟悉 C# 和 WPF 之外,我没有什么比这更好的事情要做了,所以我决定制作一些带有可视化图形的简单应用程序。所以我想把“节点”放在画布上,然后移动它,通过边等连接。 但我不知道如何检测是否单击了某个“节点”。 我注意到Ellipse 对象中有.MouseDown,但在这种情况下不知道如何使用它(只是if (ellipse.MouseDown) 是正确的)

xaml:

<Window x:Class="GraphWpf.View"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="View" Height="400" Width="700" ResizeMode="NoResize">
    <Grid>
        <Canvas x:Name="canvas" MouseDown="Canvas_MouseDown" Background="#227FF2C5" Margin="0,0,107,0" />
        <CheckBox Content="Put nodes" Height="32" HorizontalAlignment="Left" Margin="591,67,0,0" Name="putNodes" VerticalAlignment="Top" Width="75" />
    </Grid>
</Window>

cs代码:

public partial class View : Window
    {


        public View()
        {
            InitializeComponent();
        }

        private Point startPoint;
        private Ellipse test;

        List<Ellipse> nodesOnCanv = new List<Ellipse>();

        private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(canvas);

            if ((bool)putNodes.IsChecked)
            {

                test = new Ellipse();
                test.Fill = new SolidColorBrush(Colors.Blue);
                test.Width = 20;
                test.Height = 20;

                var x = startPoint.X;
                var y = startPoint.Y;

                Canvas.SetLeft(test, x);
                Canvas.SetTop(test, y);

                canvas.Children.Add(test);
                nodesOnCanv.Add(test);

            }
            else { 
                foreach(Ellipse element in nodesOnCanv){ //such statment is incorrect
                    if (element.MouseDown()) { 
                      //do something
                    }
                }
            }
        }
    } 

【问题讨论】:

    标签: c# wpf canvas mousedown


    【解决方案1】:

    你可以使用IsMouseOver Property

    foreach (Ellipse element in nodesOnCanv)
    {
       if (element.IsMouseOver)
       {
          element.Fill = Brushes.Red;
       }
    }
    

    或为每个节点处理 MouseDown

    test = new Ellipse();
    test.MouseDown += new MouseButtonEventHandler(test_MouseDown);
    

    .

    void test_MouseDown(object sender, MouseButtonEventArgs e)
    {
        (sender as Ellipse).Fill = Brushes.Red;
    }
    

    我更喜欢后者。

    【讨论】:

    • 因为你不会遍历所有元素来找到正确的节点。
    猜你喜欢
    • 1970-01-01
    • 2016-12-13
    • 2023-03-30
    • 1970-01-01
    • 2018-08-20
    • 2023-03-24
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    相关资源
    最近更新 更多