Silverlight 3 DataForm ValueConverter - Add Extensibility

A recent post described how to obtain extensibility, with respect to DataForm Control Mapping:

http://weblogs.asp.net/naughton/archive/2009/08/01/silverlight-3-dataform-control-mapping-add-extensibility.aspx

It is also convenient to make the DataFormValueConverter feature extensible.

The DataFormValueConverter class is used by the DataField as the default binding.Converter setting.

If we want to have more control over the IValueConverter implementation that gets used by default, we can add a property to DataForm:

public IValueConverter DataFormValueConverter { get; set; }

Then, we need to adjust the DataField.UpdateBindingsOnElement method:

Old:

if (binding.Converter == null)

{

binding.Converter =
new DataFormValueConverter();

}

New:

if (binding.Converter == null)

{

//binding.Converter = new DataFormValueConverter();

IValueConverter dataFormValueConverter = null;

DataForm parentDataForm = this.GetParentDataForm();

if (null != parentDataForm)

{

dataFormValueConverter = parentDataForm.DataFormValueConverter;

if (null == dataFormValueConverter)

{

dataFormValueConverter =
new DataFormValueConverter();

}

}

else

{

dataFormValueConverter =
new DataFormValueConverter();

}

binding.Converter = dataFormValueConverter;

}

Now, in a derived DataForm, I can supply my preferred IValueConverter. For example, I want my IValueConverter to map an empty TextBox.Text to null on the underlying string property:

The difference between DataFormValueConverter and my class (DataFormExtendedValueConverter) is in bold below:

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

{

if (targetType != null && (IsNullableType(targetType) || targetType == typeof(string)))

{

String strValue = value as String;if (strValue != null && strValue.Length == 0)

{

return null;

}

}

return value;

}

 

No Comments