Search code examples
c#wpfeventscanvasmousedown

WPF: canvas and shapes mouse events not working


I have a canvas object with many ellipses generated in code. I set up the event handlers for MouseDown. However, it wasn't working. I dig in this a lot and I ended with a very simple situation: I have a window with a Grid as root and a canvas inside:

XML:

<Window x:Class="SQLparserTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="900" Width="1280" >
<Grid>
    <Canvas x:Name="canvas" MouseDown="canvasMouseDown" Background="Red">
    </Canvas>
    <TextBlock x:Name="tooltip" Margin="10">0</TextBlock>
    <Button x:Name="b" Width="10" Height="10" HorizontalAlignment="Left" VerticalAlignment="Top" Click="buttonClick"/>        
</Grid>
</Window>

And generated handler in code:

 private void canvasMouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("MouseDown");
        }

Most of solutions I was able to find talk about setting a background color instead of null. But my code is not working (the event never fires).

Can somebody please tell me why it is not working?

Thank you.


Solution

  • Since the TextBlock is over on canvas.
    If you don't set size of TextBlock, it is stretched.

    Maybe if you click most edge, then the message box called.
    You can confirm text block size by setting background of textblock.

    Or you should set a property named IsHitTestVisible to False.
    like

    <TextBlock x:Name="tooltip" Margin="10" IsHitTestVisible="False">0</TextBlock>