【问题标题】:Bind controls with Model object in ViewModel class in Xamarin forms将控件与 Xamarin 表单中 ViewModel 类中的模型对象绑定
【发布时间】:2020-01-22 08:45:39
【问题描述】:

我正在使用 Prism 以 Xamarin 形式学习 MVVM。我已经实现了一个使用用户模型类的登录功能。但是绑定不起作用。请检查代码并提出更正建议。

我不确定如何将控件的文本属性绑定到模型类对象的属性。

LoginPage.xaml

   <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="http://prismlibrary.com"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="LeaveTracker.Views.LoginPage"
             Title="{Binding Title}">

    <StackLayout Orientation="Vertical" BindingContext="{Binding UserObj}">
        <Entry Placeholder="User ID" Text="{Binding UserID}"/>
        <Entry Placeholder="Password" Text="{Binding Password}" IsPassword="True"/>
    </StackLayout>
</ContentPage>

LoginPageViewModel.cs

 public class LoginPageViewModel : ViewModelBase
    {
        private User _user;
        private IFirebaseService _firebaseService;

        public User UserObj
        {
            get { return _user; }
            set { SetProperty(ref _user, value); }
        }

        public DelegateCommand LoginCommand { get; set; }

        public LoginPageViewModel(IFirebaseService firebaseService, INavigationService navigationService) : base(navigationService)
        {
            Title = "Log In";
            _firebaseService = firebaseService;
            LoginCommand = new DelegateCommand(Login, CanLogin);
        }

        private void Login()
        {
            var x = _firebaseService.LoginAsync(_user);
        }

        private bool CanLogin()
        {
            if (string.IsNullOrEmpty(_user.UserID) && string.IsNullOrEmpty(_user.Password))
            {
                return true;
            }

            return false;
        }

User.cs

  public class User
    {
        private string _userID;

        public string UserID
        {
            get { return _userID; }
            set { _userID = value; }
        }

        private string _password;

        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }



    }

【问题讨论】:

    标签: xamarin mvvm xamarin.forms prism


    【解决方案1】:

    你的BindingContextLoginPageViewModel,而UserObj是VM的一个属性,所以你的绑定路径需要包含UserObj

    <Entry Placeholder="User ID" Text="{Binding UserObj.UserID}"/>
    <Entry Placeholder="Password" Text="{Binding UserObj.Password}" IsPassword="True"/>
    

    【讨论】:

    • 我试过这种方法。它不起作用,当我在 SetProperty 方法调用上放置断点时,它不会被命中。同样在登录方法中,将 _user 设为 null。
    • 你需要初始化 User 使其不为空
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2018-02-12
    相关资源
    最近更新 更多