后端 Xamarin Forms 建立可以绑定属性的方法 ~ 少爷的博客

yue1132 · March 08, 2020 · 23 hits

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

[RenderWith(typeof(_ActivityIndicatorRenderer))]
    public class ActivityIndicator : View, IElementConfiguration<ActivityIndicator>
    {
        //这就是值类型绑定的实现
        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<ActivityIndicator>> _platformConfigurationRegistry;

        public ActivityIndicator()
        {
            _platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<ActivityIndicator>>(() => new PlatformConfigurationRegistry<ActivityIndicator>(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<T, ActivityIndicator> On<T>() where T : IConfigPlatform
        {
            return _platformConfigurationRegistry.Value.On<T>();
        }
    }

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

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

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

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

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

用法:

View

<MyEntry MyCommand={ Binding ThisCommand ></MyEntry>

ViewModel

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


XamarinForms

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0 协议 。转载请注明出处!

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.