Wednesday, December 2, 2015

How to use ValueConverter (Decimal Converter) during data binding with control?

Scenario:

While using DevExpress WPF control, sometimes it requires to convert the binding value according to the control’s property. In that case we need use the Value Converters in this case.
Let we require to bind the SpinEdit WPF control edit value property with some object property which require to be converted to decimal value. To do that we need to follow below steps:

  1. Create a custom converter class which implements IValueConverter to convert the value to the decimal.
    namespace DevExWpfApp
    {
    public class DecimalConverter : IValueConverter
    {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
    return System.Convert.ToDecimal(value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
    throw new NotImplementedException();
    }
    }
    }

  2. Now use it in the XAML by declare it as resources and then call it as below:

    <UserControl.Resources>
    <local:DecimalConverter x:Key="DecimalConverter"/>
    </UserControl.Resources>

    <dxe:SpinEdit EditValue="{Binding Entity.MaxValue, Converter={StaticResource DecimalConverter}" />

No comments :

Post a Comment