Articles in this section
Category / Section

How to implement a converter in .NET MAUI DataForm (SfDataForm)?

2 mins read

The Syncfusion® .NET MAUI DataForm (SfDataForm) allows you to implement converters programmatically. Below is a demonstration of how to use a converter to manipulate data values before reading and saving them in the DataForm.

C#:

Use DataFormValueConverter attribute to convert the value before it is read or saved in the DataForm.

public class DataFormModel
{
  [DataFormValueConverter(typeof(StringToDateTimeConverter))]
  [DataType(DataType.Date)]
  public string DateTime { get; set; }
}

C#:

Create a converter class that implements the conversion logic from a string to a DateTime value and vice versa.

public class StringToDateTimeConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
       if (value == null || string.IsNullOrEmpty(value.ToString()))
       {
           return DateTime.Now;
       }
       else
       {
           DateTime dateTime;
           DateTime.TryParse((string)value, out dateTime);
           return dateTime;
       }
   }
   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
       return value.ToString();
   }
}

C#:

Initialize the DataFormModel in the DataFormViewModel class.

public class DataFormViewModel
{
   public DataFormModel DataFormModel { get; set; }

   public DataFormViewModel()
   {
       this.DataFormModel = new DataFormModel();
   }
}

XAML:

Create a Dataform and bind the DataFormModel as its DataObject.

<ContentPage.BindingContext>
   <local:DataFormViewModel/>
</ContentPage.BindingContext>

<dataForm:SfDataForm x:Name="dataForm" DataObject="{Binding DataFormModel}"/>

Download the complete sample from GitHub.

Output:

Converter.png

Conclusion:

I hope you enjoyed learning how to programmatically implement converter in the .NET MAUI DataForm (SfDataForm).

Refer to our .NET MAUI DataForm feature tour page for its other groundbreaking feature representations. You can also explore our .NET MAUI DataForm documentation to understand how to present and manipulate data.

For current customers, check out our .NET MAUI components from the License and Downloads page. If you are new to Syncfusion®, try our 30-day free trial to check out our .NET MAUI DataForm and other .NET MAUI components.

Please let us know in the following comments section if you have any queries or require clarifications. Contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied