How do I use BindableProperty.Create in Xamarin.Forms?
In the xaml in Xamarin.Forms, I have a custom control, I want to add a type property int
. I think I need to use the Bindable properties, so I can later bind the property to the ViewModel.
I found this thread , but I'm not sure how to use it .. there is:
BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(BindablePicker), null,
propertyChanged: OnItemsSourcePropertyChanged);
what is "BindablePicker"? Is this the view in which the property is declared?
Here's my attempt:
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 haven't even used it in xaml and it doesn't work anymore. There is no particular exception. Only the page on which the custom control is initialized does not qualify. When I comment out the line I pasted here it works.
source to share
Your code is good, just change the default null
to 0 or default(int)
. You have it like null
, but the property can int
never be null. This was the cause of the "accident".
public static readonly BindableProperty WedgeRatingProperty =
BindableProperty.Create (nameof (WedgeRating), typeof (int), typeof (GameCocosSharpView), default(int), propertyChanged: OnItemsSourcePropertyChanged);
Hope this helps!
source to share
Here is an example for the Bindable property
public class GameCocosSharpView : View
{
public int WedgeRating
{
get { return (int)GetValue(WedgeRatingProperty); }
set { SetValue(WedgeRatingProperty, value); }
}
public static void WedgeRatingChanged(BindableObject bindable, object oldValue, object newValue)
{
}
public static readonly BindableProperty WedgeRatingProperty =
BindableProperty.Create("WedgeRating", typeof(int), typeof(GameCocosSharpView), 1, BindingMode.Default, null, WedgeRatingChanged);
}
source to share