mvvmcross touch command binding in android

前端 未结 1 1700
日久生厌
日久生厌 2020-12-10 21:05

I\'m looking for a way to do a \"Touch\" command binding between axml and ViewModel, or some else like FocusChanged etc.

A simple \"Click\" command works fine like s

相关标签:
1条回答
  • 2020-12-10 21:22

    The framework can automatically bind any events which require EventHandler types. However, for any events which require a templated EventHandler (with custom EventArgs) then you are correct - you'll need to include a custom Binding.

    The good news is that custom bindings are easy to write and to include.

    For example, to bind:

    public event EventHandler<View.LongClickEventArgs> LongClick;
    

    you can include something like:

    public class LongPressEventBinding
        : MvxBaseAndroidTargetBinding
    {
        private readonly View _view;
        private IMvxCommand _command;
    
        public LongPressEventBinding(View view)
        {
            _view = view;
            _view.LongClick += ViewOnLongClick;
        }
    
        private void ViewOnLongClick(object sender, View.LongClickEventArgs eventArgs)
        {
            if (_command != null)
            {
                _command.Execute();
            }
        }
    
        public override void SetValue(object value)
        {
            _command = (IMvxCommand)value;
        }
    
        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                _view.Click -= ViewOnLongClick;
            }
            base.Dispose(isDisposing);
        }
    
        public override Type TargetType
        {
            get { return typeof(IMvxCommand); }
        }
    
        public override MvxBindingMode DefaultMode
        {
            get { return MvxBindingMode.OneWay; }
        }
    }
    

    Which can be configured in setup using something like:

        protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
        {
            base.FillTargetFactories(registry);
    
            registry.RegisterFactory(new MvxCustomBindingFactory<View>("LongPress", view => new LongPressEventBinding(view)));
        }
    

    Note that you can't write a single class that binds to all the different event types - as the compiler requires you to include the correct Type for the EventArgs. However, you could fairly easily change public class LongClickEventBinding to something like public class CustomEventBinding<TViewType, TEventArgsType> if you wanted to.


    With regards to what argument you should pass into the IMvxCommand Execute method, I guess this depends a bit on the method in question, and it also depends on whether you need the ViewModel to support multiple platforms, or whether it is just for Android.

    0 讨论(0)
提交回复
热议问题