[英]Why Canvas wpf doesn't detect click?
This is my XAML 这是我的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 ......这是我的C#代码
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. 谢谢。
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. Canvas
永远不会自动调整其大小到内容,即使它确实没有内容,所以删除Height="Auto"
并让它填充所有可用空间。 Second problem is that Background
of the Canvas
won't be initialized (default null value) hence it won't be hit test visible. 第二个问题是
Canvas
Background
将不会被初始化(默认空值)因此它不会被命中测试可见。 You need to initialize Background
to something, Transparent
for example 您需要将
Background
初始化为某些内容,例如Transparent
<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
. 当你
GetPosition
你指定相对于哪一个元素(在你的情况,你通过cnv
),所以如果你会改变Margin
的cnv
它会回报你的位置上,区域的左上角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) 您可以通过更改测试
Margin
和Background
,以红色为例,的Canvas
,并单击顶部,红色矩形的左上角Mouse.GetPosition(cnv)
将始终返回你的价值接近于零(不管什么是保证金)
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?
你能尝试将每个高度设置为175并告诉它是否有帮助吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.