设置完在Canvas的位置后,控件HitTest不响应的问题

have a Canvas with a couple of elements on it like Line, Path and Text Box. In the MouseOver event of the Canvas there's a HitTest for all of them like:

bool HitTest( Point p )
{
  return VisualTreeHelper.HitTest( textBox, p ) != null;
}

This works pixel-accurate for Line and Path, but does not work as expected for Text Box.

For example when the TextBox is positioned at 50, 50 like this:

Canvas.SetLeft( textBox, 50.0 );
Canvas.SetTop( textBox, 50.0 );

it is drawn at that position correctly: if the text is about 20 pixels high and 50 pixels wide, the bounding rectangle on the screen is roughly L=50 T=50 R=100 B=70.

However the HitTest function returns false in that rectangle and returns true only in a rectangle L=0 T=0 R=50 B=20. In other words the hit test knows the size of the Text Box but ignores it is not positioned at 0,0.

Why does this happen, and how to work around? (I have the feeling it has something to do with the fact that for positioning the Line and Path elements I do not use SetLeft/SetTop)

 

 

 

up vote2down voteaccepted

Simply because the TextBox doesn't know anything about the fact that it is positioned in a Canvas, and hence nothing about an "actual position".

When you call VisualTreeHelper.HitTest(textBox, p) the Point p is given in coordinates relative to the textBox visual. Is doesn't matter where in a Canvas or any other possible container the TextBox is located.

That you get the "right" coordinates (relative to your Canvas) for Line and Path is just because you don't set Canvas.Left or Canvas.Top on them.

In case you need the coordinates relative to the Canvas, you would usually do something like this:

bool HitTest(UIElement element, Point p)
{
    var elementPoint = new Point(
        p.X - Canvas.GetLeft(element),
        p.Y - Canvas.GetTop(element));

    return VisualTreeHelper.HitTest(element, elementPoint) != null;
}

or alternatively

bool HitTest(UIElement element, Point p)
{
    var elementPoint = canvas.TransformToDescendant(element).Transform(p);

    return VisualTreeHelper.HitTest(element, elementPoint) != null;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值