0

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

xml:

<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
                    }
                }
            }
        }
    } 
4

1 回答 1

3

您可以使用IsMouseOver 属性

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;
}

我更喜欢后者。

于 2013-06-16T10:18:40.330 回答