【问题标题】:Passing Data on Navigation在导航中传递数据
【发布时间】:2019-07-20 19:05:58
【问题描述】:

我需要在用户登录时将数据传递到主页。我需要将用户名传递到主页。

public void Login(string Username, string password)
{
    // ..... Do login and if success
    var Logindata = database.GetUsername(_usernamelogin);

    Application.Current.MainPage.Navigation.PushAsync(new Homepage(Logindata));

}

我获取用户名的方法是

public Register_person GetUsername(string mail1)
{
    return Conn.Table<Register_person>().FirstOrDefault(t => t.UserName == mail1);
}

我的主页 XAML

在我的主页代码后面的cs中,我检索传入的数据

public Register_person register_Person;
public Homepage (Register_person loindata)
{
    InitializeComponent ();
    l1.Text = logindata.UserName;
}

此代码有效,我可以获得用户名。但我正在使用 MVVM,不知道如何在 MVVM 中实现。

【问题讨论】:

  • 微软有一些示例应用。开始阅读源码here
  • 您想知道如何将您当前的项目更改为MVVM 结构吗?传递数据,也可以将值作为参数传递给homePage的构造函数。

标签: c# linq sqlite mvvm xamarin.forms


【解决方案1】:

执行此操作的纯 MVVM 方法是抽象导航并从您的视图模型中调用它(参见 Prisms navigation service 作为参考)。无论如何,在实现这样的导航服务时可能存在相当多的陷阱。如果可能的话,我建议将 Prism 集成到您的解决方案中并使用完整的 MVVM。

然而,有一种混合方法更容易实现,但不是纯粹的 MVVM。假设您没有注入依赖项,您可以直接在 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:local="clr-namespace:App1"
             xmlns:generic="clr-namespace:System.Collections.Generic;assembly=netstandard"
             x:Class="App1.MainPage"
             x:Name="Page">

    <ContentPage.BindingContext>
        <local:ViewModel />
    </ContentPage.BindingContext>

    <!-- Your content goes here -->

</ContentPage>

在您的视图模型中,您现在可以定义一个命令来让用户登录,以及一个用于向您的视图传达用户已成功登录的事件(请注意,此代码被剥离到 最低

class ViewModel
{
    /// <summary>Initializes a new instance of the <see cref="T:System.Object"></see> class.</summary>
    public ViewModel()
    {
        LogInCommand = new Command(OnLogIn);
    }

    private void OnLogIn()
    {
        // your login logic shall go here
        // your password and user name shall be bound 
        // via other properties

        // Invoke the LoggedIn event with the user name 
        // of the logged in user.
        LoggedIn?.Invoke(userName);
    }

    public event Action<string> LoggedIn;

    public Command LogInCommand { get; }
}

在你看来你可以订阅LoggedIn

<ContentPage.BindingContext>
    <local:ViewModel LoggedIn="ViewModel_OnLoggedIn" />
</ContentPage.BindingContext>

当然,您需要在您的代码中使用相应的方法(.xaml.cs 文件)

private void ViewModel_OnLoggedIn(string obj)
{
    // navigate the other page here
}

这不是您可以直接插入的解决方案,但应该为您指明正确的方向。 请注意,您必须将一些 Button 或其他内容绑定到 LogInCommand,以及用户名和密码的属性条目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2020-04-19
    • 2020-08-20
    相关资源
    最近更新 更多