Xamarin Forms 建立可以绑定属性的方法

本文讲述如何实现控件的属性如何可以被 Binding

官方例子

[RenderWith(typeof(_ActivityIndicatorRenderer))]
    public class ActivityIndicator : View, IElementConfiguration
    {
        //这就是值类型绑定的实现
        public static readonly BindableProperty IsRunningProperty = BindableProperty.Create
        ("IsRunning", typeof(bool), typeof(ActivityIndicator), default(bool));

        public static readonly BindableProperty ColorProperty = BindableProperty.Create
        ("Color", typeof(Color), typeof(ActivityIndicator), Color.Default);

        readonly Lazy> _platformConfigurationRegistry;

        public ActivityIndicator()
        {
            _platformConfigurationRegistry = new Lazy>(() => new PlatformConfigurationRegistry(this));
        }

        public Color Color
        {
            get { return (Color)GetValue(ColorProperty); }
            set { SetValue(ColorProperty, value); }
        }
        //与之对对应的属性
        public bool IsRunning
        {
            get { return (bool)GetValue(IsRunningProperty); }
            set { SetValue(IsRunningProperty, value); }
        }
        public IPlatformElementConfiguration On() where T : IConfigPlatform
        {
            return _platformConfigurationRegistry.Value.On();
        }
    }

Ps:这个官方例子是有问题的。

下面讲一下如何绑定事件,其实 Xamarin Forms 绑定事件用的是 Command,方法也不难。

public class MyEntry:Entry
{
    public ICommand MyCommand
    {
        get => (ICommand )GetValue(MyCommandProperty);
        set => SetValue(MyCommandProperty, value);
    }

    /// 
    /// MyCommandProperty的Mvvm实现
    /// 
    public static readonly BindableProperty MyCommandProperty = Create
    (
        nameof(回调方法),
        typeof(ICommand),
        typeof(MyEntry)
    ); //注意这里变量名的命名规则是MyCommand + Property,前者随便,后者固定语法

    private void 回调方法()
    {
        MyCommand?.Execute(null);
    }
}
//这样这个MyEntry的MyCommand就可以被Mvvm绑定了。

用法:

View


ViewModel

public class Model:某个mvvm框架的BasePage
{
    public Command ThisCommand
    {
        get
        {
            retrun new Command(()=>
            {
                //做点什么
            });
        }
    }
}

你可能感兴趣的:(Xamarin Forms 建立可以绑定属性的方法)