Business Forms in Silverlight Part 2

(this is a continuation of Part 1)

From the previous post:

Basic DataForm experience
Basic DataForm experience

The first problem is the OrderDate is unintialized and renders as 0/00/0000.

The first thought is to change the OrderDate from DateTime to Nullable<DateTime>. This will require either the database schema be changed, or a second viewmodel created. Changing the database schema just to support a user-interface tweak is obviously out of the question. However, writing a viewmodel and copying all the properties over breaks a rule of “DRY” (Don’t Repeat Yourself).

Luckily, XAML binding supports the notion of binding converters. This lets us transforms inputs from one type to another.

public class NullValueConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is DateTime && targetType == typeof(Nullable<DateTime>))
        {
            if ((DateTime)value == DateTime.MinValue)
            {
                return null;
            }
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

Applying the converter to the date picker, we get reasonably good results. For example, after entering a date and then clearing it, we get a validation error showing (see picture below). Furthermore, hitting cancel restores the control back to default value.

dataform2

This done, we are ready to tackle our next problem.

Aside

Here’s a sample of how converters are applied.

<sdk:DataForm>
  <sdk:DataForm.Resources>
    <local:NullValueConverter x:Key="NullValueConverter" />
  </sdk:DataForm.Resources>
  <sdk:DataField Label="Order Date">
    <sdk:DatePicker SelectedDate="{Binding OrderDate, Converter={StaticResource NullValueConverter}}" />
  </sdk:DataField>
</sdk:DataForm>