Home > Blockchain >  How to pass value from xamarin page to ivalueconverter class properties Xamarin Forms
How to pass value from xamarin page to ivalueconverter class properties Xamarin Forms

Time:06-15

I have a class of IValueConverter with a property named myValue which I want to divide the ivalueconverter by its property myValue! But, I want to know if it is possible to pass the myValue from xamarin page to ivalueconverter? If yes, how?

IvalueConverter

class salesUIbtnWidth : IValueConverter
{
    public double myValue { get; set; }
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (double)value / myValue;
    }

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

Try Implementing the class

 <Button Text="Click me" HorizontalOptions="Center" VerticalOptions="Center"
         CornerRadius="15" WidthRequest="{Binding Source={x:Reference 
         frame}, Path=Width,Converter={StaticResource salesUIbtnWidth}}">
 </Button>//how to bind also the MyValue

All I want is to know how to set myValue in page and pass it to (IvalueConverter) from xamarin during runtime!!

CodePudding user response:

You can pass the value by ConverterParameter.

You can refer to the sample code:

<Label Text="{Binding Red,
                  Converter={StaticResource doubleToInt},
                  ConverterParameter=255,
                  StringFormat='Red = {0:X2}'}" />


 <local:DoubleToIntConverter x:Key="doubleToInt" />

DoubleToIntConverter.cs

public class DoubleToIntConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (int)Math.Round((double)value * GetParameter(parameter));
    }

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

    double GetParameter(object parameter)
    {
        if (parameter is double)
            return (double)parameter;

        else if (parameter is int)
            return (int)parameter;

        else if (parameter is string)
            return double.Parse((string)parameter);

        return 1;
    }
}

For more, you can check: Binding Converter Parameters

CodePudding user response:

If you don't want to use parameter, you can define MyValue when you create the converter.

<ContentPage.Resources>
    <app1:MyConverter x:Key="myConverter" MyValue="255"/>
</ContentPage.Resources>
  • Related