Search code examples
c#wpfinkcanvas

Erase children of an InkCanvas


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?


Solution

  • 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