Mapping Converters
- 2 minutes to read
Mapping converters allow you to apply custom logic to mapping.
Overview
Converters can change data from one type to another, translate data based on additional information, or change the format in which the data is stored. To associate a value converter with a mapping, create a class that implements the IValueConverter interface and its Convert and ConvertBack methods and specify it in XAML using the Mapping.Converter property.
The data is propagated back and forth between the property, default mapping method and a data source field. You can insert a converter between the property and the default mapping method, or between default mapping method and the data source field, or instead of a default mapping method. Converter position in that propagation chain is defined by the MappingConversionBehavior enumeration.
The following image illustrates the converter’s processing order:
How to Create a Converter
The following example implements a mapping converter that returns label colors based on enumeration values:
Implement a class with a IValueConverter interface (inherited from the MarkupExtension class).
class PriorityToColorConverter : MarkupExtension, IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is Priority) { var priorityValue = (Priority)value; switch (priorityValue) { case Priority.High: return Colors.Red; case Priority.Normal: return Colors.Yellow; case Priority.Low: return Colors.Green; default: return Colors.Black; } } return Colors.Transparent; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } public override object ProvideValue(IServiceProvider serviceProvider) { return this; } }
Assign the converter to the label color mapping’s Mapping.Converter property:
<dxsch:DataSource.AppointmentLabelMappings> <dxsch:AppointmentLabelMappings Color="{dxsch:Mapping FieldName=Id, ConversionBehavior=BetweenFieldAndMapping, Converter={local:PriorityToColorConverter}}" Caption="Name" ColorSavingType="ColorInstance" Id="Id"/> </dxsch:DataSource.AppointmentLabelMappings>