Search code examples
wpfmvvminkcanvas

How to receive the InkCanvas.StrokeCollected event in the view model


In using MVVM pattern, I have a custom inkcanvas with:

   protected override void OnStrokeCollected(InkCanvasStrokeCollectedEventArgs e)
    {
        CustomStroke newStroke = new CustomStroke(e.Stroke.StylusPoints, e.Stroke.DrawingAttributes);
        this.Strokes.Remove(e.Stroke);
        this.Strokes.Add(newStroke);
        InkCanvasStrokeCollectedEventArgs eNew = new InkCanvasStrokeCollectedEventArgs(newStroke);

        // Raises the System.Windows.Controls.InkCanvas.StrokeCollected event.
        base.OnStrokeCollected(eNew);
    }

How do I get the view model to receive the InkCanvas.StrokeCollected event?

I can not bind the XAML to the strokes as the StrokeCollection.CollectionChanged event will be called three times by the custom inkcanvas.

Any help is appreciated.


Solution

  • Try this

        public Window3()
        {
            InitializeComponent();
            var vm=new ViewModel();
            this.DataContext = vm;
            canvas.StrokeCollected += vm.OnStrokeCollected;
        }
    

    ViewModel

    public class ViewModel
    {
        public void OnStrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e)
        { 
    
        }
    }
    

    Edit

    if you want to do it without codebehind see the article EventTrigger