Given that the name of your InkCanvas is InkCanvas
<InkCanvas x:Name="InkCanvas" />
To save at each stroke you can
- use the StrokesCollected and StrokesErased events
- use Application.Suspending event
Using StrokesCollected and StrokesErased this can be your Page.Loaded event handler:
private async void OnLoaded(object sender, RoutedEventArgs args)
{
InkCanvas.InkPresenter.StrokesCollected += async (presenter, eventArgs) => { await Save(); };
InkCanvas.InkPresenter.StrokesErased += async (presenter, eventArgs) => { await Save(); };
await Load();
}
Using Application.Suspending this can be your Page.Loaded event handler:
private async void OnLoaded(object sender, RoutedEventArgs args)
{
Application.Current.Suspending += async (o, suspendingEventArgs) =>
{
SuspendingDeferral deferral = suspendingEventArgs.SuspendingOperation.GetDeferral();
await Save();
deferral.Complete();
};
await Load();
}
the Save and Load methods:
private async Task Save()
{
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("strokes.ink",
CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await InkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);
await stream.FlushAsync();
}
}
private async Task Load()
{
IStorageItem storageItem = await ApplicationData.Current.LocalFolder.TryGetItemAsync("strokes.ink");
if (!(storageItem is StorageFile storageFile)) return;
using (IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read))
{
await InkCanvas.InkPresenter.StrokeContainer.LoadAsync(stream);
}
}
I'm sure that file access in the Save method can be improved, anyway this works as a basic example.