Moses Aprico
Moses Aprico

Reputation: 2121

Why Canvas wpf doesn't detect click?

This is my XAML

<Window x:Class="Drawing.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <TextBox Grid.Row="0" Height="25" IsEnabled="False" Name="txt"/>
    <Canvas Name="cnv" MouseLeftButtonDown="cnv_MouseLeftButtonDown" Grid.Row="1"/>
</Grid>
</Window>

...and this is my C# code

private void cnv_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Point p = Mouse.GetPosition(cnv);
    p.X += cnv.Margin.Left;
    p.Y += cnv.Margin.Top;
    txt.Text = p.ToString();
}

Questions :

  1. Even if I click the canvas, the event didn't even fired. I wonder why? Is there anything I missed?
  2. In this code, I haven't included any canvas margin, but since I wanna use margin later, is it necessary to add the click position with margin to get a correct value?

Thanks.

Upvotes: 1

Views: 7201

Answers (2)

dkozl
dkozl

Reputation: 33364

Canvas will never auto adjust its size to content and even if it did it has no content in your case so remove Height="Auto" and let it fill all available space. Second problem is that Background of the Canvas won't be initialized (default null value) hence it won't be hit test visible. You need to initialize Background to something, Transparent for example

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBox Grid.Row="0" Height="25" IsEnabled="False" Name="txt"/>
    <Canvas Name="cnv" MouseLeftButtonDown="cnv_MouseLeftButtonDown" Grid.Row="1" Background="Transparent"/>
</Grid>

EDIT

As for the second question. When you do GetPosition you specify relative to which element (in your case you pass cnv) so if you would change Margin on the cnv it would return you position to the top,left corner of the area of Canvas. You can test it by changing Margin and Background, to red for example, of the Canvas and clicking in top,left corner of the red rectangle and Mouse.GetPosition(cnv) will always return you value close to zero (no matter what's the margin)

Upvotes: 5

user3596113
user3596113

Reputation: 878

There might be a problem with the

Height="Auto"

Attribute of your rows. Can you try to set each Height to 175 and tell if that helped?

Upvotes: 0

Related Questions