Data Converstion and Task Addition with WPF
(Page 1 of 4 )
Welcome to the third part of a four-part series that explains WPF through an example. We're now deep into the process of building our to-do list application. We need to make it possible for someone using the application to check off tasks when they are done, and add new tasks. Keep reading to learn how we do this.
Converting Values
So, we have a CheckBox that needs to be checked or unchecked depending on whether the task is done or not done, and we have a TextBlock that needs to be colored according to the task's priority. The CheckBox contains a property called IsChecked, which is a boolean indicating whether or not the box is checked, but the XML simply contains a "Yes" or "No" string. Similarly, the TextBlock contains a Foreground property to set the color, but priority in the XML file is indicated by "Low," "Medium" or "High." We're going to have to convert the values in the XML to the correct property values, and, for the CheckBox, we need a way to convert the value of IsChecked back into a string for when the user marks a task as done.
Conversion is done by creating a class that implements the IValueConverter interface and providing the proper code for conversion between the data source and the appropriate controls. Fortunately, this interface isn't very complicated, and not a lot of code will be required. The interface calls for two methods: Convert and ConvertBack. The Convert method is called when a value is taken from the data source, and the ConvertBack method is called when a value needs to be put back into the data source.
Let's create a converter class for the CheckBox first. Create a new class in Visual Studio called StatusConverter. Create the class, implementing IValueConverter:
namespace WpfToDo
{
class StatusConverter : System.Windows.Data.IValueConverter
{
}
}
Next, we need to implement the Convert method. The Convert method takes several parameters, but only the first one is important here, since it contains the actual value that we need to convert. Remember that we'll be accepting a "Yes" or "No" string from the XML file and will need to return a boolean. This conversion can be done in a single step:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((string)value).ToLower() == "yes";
}
Above, the incoming string is converted to lower case. That way, the content of the Status element can be case insensitive.
Converting the boolean back into a string is also very simple:
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((bool)value)
{
return "Yes";
}
return "No";
}
Next: Converting Values, Continued >>
More Windows Scripting Articles
More By Peyton McCullough