Reputation: 2121
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 :
Thanks.
Upvotes: 1
Views: 7201
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
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