Completing a WPF To-Do List Application
(Page 1 of 5 )
In this conclusion to a four-part series that illustrates WPF through the example of building a to-do list application, we will complete the program we started. You will learn how to make the software handle deleting tasks, and how to give it the look and feel you want.
Deleting tasks
Now that a mechanism for the addition of new tasks has been added, the user needs a way to delete an existing task. In the code, deleting tasks is much easier than adding tasks. The element representing the selected task simply needs to be removed from the XML when the user clicks the delete button.
In Visual Studio, double click the delete button in the designer to automatically create a click event handler, or manually add it:
<Button Name="DeleteButton" Grid.Row="1" Grid.Column="1" Content="Delete Task" Click="DeleteButton_Click">
The code for deletion is really simple. First, the code needs to check that an item is indeed selected. If nothing is selected in TaskListBox, then its SelectedIndex property will be -1. So, the code simply needs to check that SelectedIndex isn't -1. If it isn't, then the value of the SelectedItem property of TaskListBox needs to be cast into an XmlElement object, and this element needs to be removed from its parent element (Tasks):
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
if (TaskListBox.SelectedIndex != -1)
{
XmlElement task = (XmlElement)TaskListBox.SelectedItem;
task.ParentNode.RemoveChild(task);
}
}
When a task is selected and the delete button is pressed, the task will now be deleted from the list.
Next: Saving the task list >>
More Windows Scripting Articles
More By Peyton McCullough