custom BindableProperty of HeightRequest for my custom control in xamarin.forms

576 Views Asked by At

I have created one custom control for wrappanel.but it shows extra space. so i am trying to create BindableProperty of HeightRequest for control and set it according to content to remove extra space.

this is how i created BindableProperty of HeightRequest

    public double HeightRequest { get; set; }

    private static BindableProperty heightTextProperty = BindableProperty.Create(
                                                     propertyName: "HeightRequest",
                                                     returnType: typeof(double),
                                                     declaringType: typeof(InstallationPhotoWrappanel),
                                                     defaultValue: 100,
                                                     defaultBindingMode: BindingMode.TwoWay,
                                                     propertyChanged: heightTextPropertyChanged);

    private static void heightTextPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var control = (InstallationPhotoWrappanel)bindable;
        control.HeightRequest = Convert.ToDouble(newValue);
    }

but it gives me exception

exception has been thrown by the target of an invocation

what i am doing wrong here.please help.

Thank you in advance.

2

There are 2 best solutions below

1
On BEST ANSWER

Your custom control should already have a HeightRequest property. I am assuming you are creating a custom bindable property with name as HeightText.

If that is so, there are three issues I can see in the code:

  1. propertyName: "HeightRequest" should be propertyName: "HeightText"

  2. To ensure we don't get target property type-mismatch exceptions, change defaultValue: 100 to defaultValue: (double)100

  3. And add a HeightText property using GetValue, and SetValue

    public double HeightText
    {
        get
        {
            return (double)GetValue(HeightTextProperty);
        }
        set
        {
            SetValue(HeightTextProperty, value);
        }
    }
    
0
On

Please have a look below code and try it. Hope, It will help you.

Code

public static readonly BindableProperty HeightRequestProperty =
    BindableProperty.Create<InstallationPhotoWrappanel,double>(i=>i.HeightRequest,100,BindingMode.TwoWay,heightTextPropertyChanged);

public double HeightRequest
{
    get
    {
        return (double)GetValue(HeightRequestProperty);
    }
    set
    {
        SetValue(HeightRequestProperty, value);
    }
}

static bool heightTextPropertyChanged(BindableObject bindable, double value)
{
    var control = (InstallationPhotoWrappanel)bindable;
    control.HeightRequest = value;
    return true;
}