1

I have a canvas, and I need to put an (for example) ellipse on it, not from XAML but from code. So I do

Ellipse e1;

public MainWindow()
    {
        ...
        ... 
        e1 = new Ellipse();
        e1.Height = 100;
        e1.Width = 100;
        e1.Stroke = Brushes.Red;
        e1.StrokeThickness = 5;
        Canvas.SetLeft(e1,40);
        Canvas.SetTop(e1,50);
        e1.MouseDown += ellipse_MouseDown;
        Canvas1.Children.Add(e1);

    }

   private void ellipse_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Ellipse el = (Ellipse)sender;
        el.Stroke = Brushes.Green;
        buttonAdd.Content = "New_TEXT";

    }

But it doesn't react on clicking. Anyway, I tried to add this ellipse_MouseDownmethod to ellipse that was created from XAML - and it works.

 <Canvas x:Name="Canvas1" HorizontalAlignment="Left" Height="421" Margin="10,10,0,0" VerticalAlignment="Top" Width="346">
      <Ellipse x:Name="ellipse" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="111" Margin="117,152,0,0" Stroke="Black" VerticalAlignment="Top" Width="131" MouseDown="ellipse_MouseDown" MouseMove="ellipse_MouseMove" MouseUp="ellipse_MouseUp"/>
  </Canvas>

Where can be a problem?

UPD.

According to Rohit Vats's answer just add

e1.Fill = Brushes.Transparent;

or

e1.Fill = new SolidColorBrush((Color)ColorConverter
                                       .ConvertFromString("#FFF4F4F5"));

'cause by default Fill is null which doesn't respond to mouse events

1
  • Please show the XAML that works, so we can compare it with the code that doesn't. Commented Dec 14, 2013 at 8:59

1 Answer 1

1

You need to set Fill to Transparent so that it can react to mouse events. By default Fill is null which doesn't respond to mouse events -

e1.Stroke = Brushes.Red;
e1.Fill = Brushes.Transparent; <-- HERE

UPDATE

As evident from XAML code, you are setting Fill to #FFF4F4F5 but not setting it from code behind.

e1.Fill = new SolidColorBrush((Color)ColorConverter
                                       .ConvertFromString("#FFF4F4F5"));
Sign up to request clarification or add additional context in comments.

1 Comment

Great. I have update with Fill color in case you don't want it to be transparent. Hope it resolves your query. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.