4

I have an InkCanvas on a window in which I allow the user to draw with a stylus, touch, or mouse. I also allow the user to add text. The user taps an "add text" button, then taps where on the canvas they would like their text. A textbox appears there, allowing them to type. On enter or lost focus I create a ContentControl and add it to myInkCanvas.Children.

I would like the user to be able to erase the text they have created when the InkCanvas is in erase mode (I am using EraseByPoint). I've attempted to capture the MouseEnter and PreviewMouseMove events of the content controls, but neither seem to fire.

Is there an event that I can capture? Is there a better way to handle this scenario? Is it even possible?

Navid Rahmani
  • 7,848
  • 9
  • 39
  • 57
Ricky Smith
  • 2,379
  • 1
  • 13
  • 29

1 Answers1

4

You can use hit testing for this purpose
look at here

get InkPresenter first

public T GetVisualChild<T>(Visual parent) where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
        {
            child = GetVisualChild<T>(v);
        }
        if (child != null)
            break;
    }
    return child;
}

InkPresenter inkPresenter = GetVisualChild<InkPresenter>(myInkCanvas);

then get HitTestResult of your Point

HitTestResult hitTestResult = VisualTreeHelper.HitTest(inkPresenter, new Point(x, y));

then you can use hitTestResult.VisualHit to remove this object

Navid Rahmani
  • 7,848
  • 9
  • 39
  • 57
  • So, I would need to capture a mouse event on the inkcanvas and on each event perform the hit test on each child of the inkcanvas? – Ricky Smith Jun 17 '11 at 13:58
  • Looks cool. I can't seem to find a generic version of GetVisualChild. What namespace is that in? – Ricky Smith Jun 17 '11 at 14:04
  • Not a problem. I ended up creating one that was similar (but not as good) as your's. – Ricky Smith Jun 17 '11 at 14:12
  • 1
    Everything is working with the hit testing. I'm making an EllipseGeometry that matches the size/shape of the eraser cursor for the hit parameter. In the HitTestResultCallback I'm using `myInkCanvas.Children.Remove((UIElement)result.VisualHit);` but the child element isn't being removed from the inkcanvas. Any ideas? – Ricky Smith Jun 17 '11 at 14:45
  • 1
    Yes sure you can use [GeometryHitTestParameters](http://msdn.microsoft.com/en-us/library/system.windows.media.geometryhittestparameters.aspx) – Navid Rahmani Jun 17 '11 at 14:59