Saving the pen gallery was not very complicated, but there were some unfortunate complexities. The major complexity was how to initiate a change to the pen gallery. The standard UWP InkToolbar does not provide any events relevant to if or when the user changes any of the tool’s drawing attributes.
When to save
Obviously Ink Calendar should save the Pen Gallery when the users adds a new pen, deletes a pen, or moves the location of a pen. However it is also important that changes to the pen’s properties get saved when they are changed.
The way I decided to trigger this save was on ink saving. This means when the user navigates or inks the SaveInk method runs and that would trigger the SaveCustomPens method to fire.
To keep Ink Calendar from saving the custom pen file every time ink was saved the beginning of the SaveCustomPens method checks to make sure there are changes to save. If there are changes then the current InkToolbar is converted into an array and saved to a .XML file.
Convert the InkToolbar into an array
Before the pen gallery can be saved to a file it is converted to a simple List<string>. This is done by iterating through each button and saving an entry in a new string array for the type of pen (ballpoint, highlighter, or pencil), the selected brush index, and the stroke width, and a Pen ID.
There is another method which takes the data from this type of array and adds InkToolbarCustomPen to the InkToolbar.
Saving the List to .XML
The next step was simple, pass the List<string> to a method which saves it to the app’s directory. DotNET has some very easy APIs for serializing data and saving it to a file.
public static async Task SaveCustomButtons(List<string> listToSave)
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("CustomToolButtons.xml", CreationCollisionOption.ReplaceExisting);
XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
using (Stream fs = await file.OpenStreamForWriteAsync())
TextWriter textWriter = new StreamWriter(fs);
This is a sample method of how I save data throughout Ink Calendar. Right now the data generated by the app is fairly simple and low volume. Eventually Ink Calendar could grow to a point where it needs a SQLite database but for now .XML does the trick.
Thanks for reading and let me know if you have any questions or comments. Next I’ll talk about how I enabled the pen gallery to be edited on all form factors.