Question

Well, because I have nothing better else to do than getting familiar with C# and WPF I decided to make some simple app with graph with visualisation. So I want to put "nodes" on canvas, and move it, connect by edges e.t.c. But I don't know how to detect if some "node" is clicked. I noticed that there's .MouseDown in Ellipse object but don't know how to use it (just if (ellipse.MouseDown) is mot correct) in this situation

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 code:

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
                    }
                }
            }
        }
    } 
Was it helpful?

Solution

You could use IsMouseOver Property

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

or handle MouseDown for each node

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

.

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

I would prefer the latter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top