MvvmCross - 在viewmodel中单击句柄按钮

时间:2016-07-21 09:30:57

标签: c# ios mvvm

我是xamarin和mvvmcross的新手,我想从我的ios项目中点击一个简单的按钮点击我的视图模型。

using System;
using MvvmCross.Binding.BindingContext;
using MvvmCross.iOS.Views;
using Colingual.Core.ViewModels;

namespace Colingual.iOS
{
    public partial class LoginView : MvxViewController
    {
        public LoginView() : base("LoginView", null)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            var set = this.CreateBindingSet<LoginView, LoginViewModel>();
            set.Bind(Username).To(vm => vm.Username);
            set.Bind(Password).To(vm => vm.Password);
            set.Bind(btnLogin).To(vm => vm.MyAwesomeCommand);
            set.Apply();
        }


        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
            // Release any cached data, images, etc that aren't in use.
        }
    }
}

我想将btnlogin连接到myawesomecommand。

using MvvmCross.Core.ViewModels;

namespace Colingual.Core.ViewModels
{
    public class LoginViewModel : MvxViewModel
    {
        readonly IAuthenticationService _authenticationService;

        public LoginViewModel(IAuthenticationService authenticationService)
        {
            _authenticationService = authenticationService;
        }

        string _username = string.Empty;
        public string Username
        {
            get { return _username; }
            set { SetProperty(ref _username, value); }
        }

        string _password = string.Empty;
        public string Password
        {
            get { return _password; }
            set { SetProperty(ref _password, value); }
        }



        public bool AuthenticateUser() {
            return true;
        }

        MvxCommand _myAwesomeCommand;


        public IMvxCommand MyAwesomeCommand
        {
            get
            {
                DoStuff();
                return _myAwesomeCommand;
            }
        }

        void DoStuff()
        {
            string test = string.Empty;
        }
    }
}

正如您所看到的,我的mvxCommand名称为MyAwesomecommand,但我希望通过其他项目中的按钮单击来处理某些逻辑。有人知道我应该做什么吗?

1 个答案:

答案 0 :(得分:5)

我做了更多的环顾四周并找到了answer here

MvxCommand _myAwesomeCommand;

        public IMvxCommand MyAwesomeCommand
        {
            get { return new MvxCommand(DoStuff); }
        }

        void DoStuff()
        {
            string test = string.Empty;
        }

我们的想法是让你的mvxcommand getter返回一个新方法,将该方法作为参数。

单击按钮btnLogin时,可以在viewmodel中访问void DoStuff。