Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use BindableProperty.Create in Xamarin.Forms?

In xaml in Xamarin.Forms, I have a custom control, I want to add property of type int. I think I have to use Bindable properties, so later I can bind a property from ViewModel.

I found this topic, but I'm not sure how to use it.. there is:

BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(BindablePicker), null,
    propertyChanged: OnItemsSourcePropertyChanged);

what's "BindablePicker"? Is it the view where property is declared?

Here's my try:

    public int WedgeRating
    {
        get
        {
            return (int)GetValue(WedgeRatingProperty);
        }
        set
        {
            try
            {
                SetValue(WedgeRatingProperty, value);
            }
            catch (ArgumentException ex)
            {
                // We need to do something here to let the user know
                // the value passed in failed databinding validation
            }
        }
    }

    public static readonly BindableProperty WedgeRatingProperty =
       BindableProperty.Create(nameof(WedgeRating), typeof(int), typeof(GameCocosSharpView), null, propertyChanged: OnItemsSourcePropertyChanged);

    private static void OnItemsSourcePropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
    }

I didn't even use it in xaml, and it already doesn't work. No particular exception. Only the page where the custom control is initialized doesn't loead. When I comment line I pasted here, it works.

like image 697
Ish Thomas Avatar asked Jun 07 '17 03:06

Ish Thomas


1 Answers

Your code is good, just change your default value from null to 0 or default(int). You have it as null but an int property could never be null. This was the reason of the "crash".

public static readonly BindableProperty WedgeRatingProperty =
    BindableProperty.Create (nameof (WedgeRating), typeof (int), typeof (GameCocosSharpView), default(int), propertyChanged: OnItemsSourcePropertyChanged);

Hope this helps!

like image 130
pinedax Avatar answered Oct 16 '22 03:10

pinedax