如何在Xamarin.Forms中使用BindableProperty.Create?

6
在Xamarin.Forms中的XAML中,我有一个自定义控件,我想添加一个类型为int的属性。我认为我必须使用可绑定的属性,这样我以后就可以从ViewModel绑定属性。
我找到了这个话题,但我不确定如何使用它...里面有:
BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(BindablePicker), null,
    propertyChanged: OnItemsSourcePropertyChanged);

"BindablePicker"是什么?它是声明属性的视图吗?
我的翻译如下:

“BindablePicker”是什么?它是用于声明属性的视图吗?

    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)
    {
    }

我甚至没有在xaml中使用它,它就已经无法工作了。没有任何特定的异常。只有在初始化自定义控件的页面不加载时。当我注释掉我贴在这里的那一行时,它可以工作。

2个回答

7
你的代码很好,只需要将默认值从null更改为0或 default(int)。你当前使用的是null,但是一个int属性永远不可能是null。这就是“崩溃”的原因。
public static readonly BindableProperty WedgeRatingProperty =
    BindableProperty.Create (nameof (WedgeRating), typeof (int), typeof (GameCocosSharpView), default(int), propertyChanged: OnItemsSourcePropertyChanged);

希望这能有所帮助!

7
这里是可绑定属性的示例。
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);

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接