Completing a WPF To-Do List Application - Saving the task list
(Page 2 of 5 )
You've probably noticed that even though tasks can be added to and deleted from the list, the changes are erased when the program is closed. This is because with an XML data source, the binding really only goes one way. Any changes are actually only saved to an in-memory XML document, not the original source file.
However, it's not very difficult to work around this. We simply need to add code that writes the in-memory document to the physical XML file. Perhaps the easiest way to do this is to write the changes when the application is closed, although a more complex system would be better in a real application.
In the XAML for Window1, add an attribute pointing to a handler for the Closing event:
<Window x:Class="WpfToDo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfToDo"
Closing="Window_Closing"
Title="To-Do List" SnapsToDevicePixels="true" Height="480" Width="384">
The code for this handler is pretty straightforward. The XmlDataSource needs to be fetched, and the XML document needs to be saved on disk:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
XmlDataProvider tasks = (XmlDataProvider)FindResource("tasks");
tasks.Document.Save("Tasks.xml");
}
Now changes to the application will be saved when the main window is closed, and, functionally, the application is complete.
Next: Stylizing the application >>
More Windows Scripting Articles
More By Peyton McCullough