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

Ish*_*mas 5 .net c# xamarin.ios xamarin xamarin.forms

在Xamarin.Forms的xaml中,我有一个自定义控件,我想添加类型的属性int.我想我必须使用Bindable属性,所以稍后我可以从ViewModel绑定一个属性.

我发现了这个话题,但我不确定如何使用它..有:

BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(BindablePicker), null,
    propertyChanged: OnItemsSourcePropertyChanged);
Run Code Online (Sandbox Code Playgroud)

什么是"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)
    {
    }
Run Code Online (Sandbox Code Playgroud)

我甚至没有在xaml中使用它,它已经不起作用了.没有特别的例外.只有初始化自定义控件的页面才会出现.当我评论粘贴在这里的线时,它有效.

Ven*_*ana 6

以下是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);

    }
Run Code Online (Sandbox Code Playgroud)


pin*_*dax 5

您的代码很好,只需将默认值更改null为0或default(int).你拥有它,nullint属性永远不会为null.这就是"崩溃"的原因.

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

希望这可以帮助!