美文网首页
Xamarin Forms 建立可以绑定属性的方法

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

作者: 本大少_ | 来源:发表于2017-06-19 22:59 被阅读0次

    本文讲述如何实现控件的属性如何可以被 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(()=>
                {
                    //做点什么
                });
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Xamarin Forms 建立可以绑定属性的方法

          本文链接:https://www.haomeiwen.com/subject/pvknqxtx.html