Xamarin MVVM passing data to other view

2019-03-06 03:11发布

问题:

I want to pass the data to another view page. So far I can get the data I need to pass. My problem is how do I pass the data in MVVM. I used Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(), true); When I add contactId inside DatabaseSyncPage() an error occurs. "The error is 'DatabaseSyncPage' does not contain a constructor that takes 1 arguments"

My code:

LoginPageViewModel.cs

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Input;
using TBSMobileApplication.Data;
using TBSMobileApplication.View;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace TBSMobileApplication.ViewModel
{
    public class LoginPageViewModel : INotifyPropertyChanged
    {
        void OnProperyChanged(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

        public string username;
        public string password;

        public string Username
        {
            get { return username; }
            set
            {
                username = value;
                OnProperyChanged(nameof(Username));
            }
        }

        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                OnProperyChanged(nameof(Password));
            }
        }

        public class LoggedInUser
        {
            public string ContactID { get; set; }
        }

        public ICommand LoginCommand { get; set; }

        public LoginPageViewModel()
        {
            LoginCommand = new Command(OnLogin);
        }

        public void OnLogin()
        {
            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
            {
                MessagingCenter.Send(this, "Login Alert", Username);
            }
            else
            {
                var current = Connectivity.NetworkAccess;

                if (current == NetworkAccess.Internet)
                {
                    var link = "http://192.168.1.25:7777/TBS/test.php?User=" + Username + "&Password=" + Password;
                    var request = HttpWebRequest.Create(string.Format(@link));
                    request.ContentType = "application/json";
                    request.Method = "GET";

                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
                        }
                        else
                        {
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                var content = reader.ReadToEnd();

                                if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
                            {
                                MessagingCenter.Send(this, "Http", Username);
                            }
                            else
                            {
                                var result = JsonConvert.DeserializeObject<List<LoggedInUser>>(content);
                                var contactId = result[0].ContactID;
                                Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage { myId = contactId }, true);
                            }
                        }
                    }
                }
                else
                {
                    MessagingCenter.Send(this, "Not Connected", Username);
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

DatabaseSyncPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TBSMobileApplication.View
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DatabaseSyncPage : ContentPage
    {
        public int myId { get; set; }

         public DatabaseSyncPage ()
         {
             InitializeComponent ();
             DisplayAlert("Message", Convert.ToString(myId), "ok");
         }
    }
}

回答1:

If you want to send the int. First declare that in your DatabaseSyncPage Like below

public partial class DatabaseSyncPage : ContentPage
{
    public DatabaseSyncPage( int Id)
    {
    }
}

& when you are pushing your page in your code else block do like this

if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
{
    MessagingCenter.Send(this, "Http", Username);
}
else
{
    var result = JsonConvert.DeserializeObject<List<LoggedInUser>>(content);
    var contactId = result[0].ContactID;
    Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(contactId), true);
}


回答2:

I'm assuming that contactID is an int.

Create an additional constructor in your DatabaseSyncPage:

public DatabaseSyncPage (int contactID)
{
    // TODO: Do something with your id
}

But this passes the data to the page, not the page model. Are you using any kind of framework? It would probably be worth looking into that.



回答3:

You can use xamrin.plugins.settings nuget package.