【问题标题】:Why is the data from messagingcenter not being sent over为什么没有发送来自消息中心的数据
【发布时间】:2021-12-31 01:37:55
【问题描述】:

我是 C# 新手,在 xamarin 中工作。我正在尝试加载要在应用程序中传递的用户,以便在您使用该应用程序时仅为该用户构建配置文件。我现在并不关心或优化我只想知道为什么这不起作用。代码如下所示。

从登录加载用户

private async void LoginButton_Clicked1(object sender, EventArgs e)
{
    User user = new User();
    if (userNameEntry.Text == null || passwordNameEntry.Text == null)
    {
        await DisplayAlert("No info", "Please fill out UserName and Password", "Ok");
    }
    else
    {
        if (users != null)
        {
            if (users.Exists(x => x.UserName.ToLower() == userNameEntry.Text.ToLower()))
            {
                user = users.Find(x => x.UserName.ToLower().Contains(userNameEntry.Text.ToLower()));
                if (user.Password != passwordNameEntry.Text)
                {
                    await DisplayAlert("Password MisMatch", "Password don't match. Try again!", "OK");
                    passwordNameEntry.Text = null;
                }
                else
                {
                    await Shell.Current.GoToAsync($"//{nameof(FeedPage)}");
                    MessagingCenter.Send(user, "CurrentUser");
                    userNameEntry.Text = null;
                    passwordNameEntry.Text = null;
                }
            }
        }
    }
}

试图将该用户加载到应用程序的其他位置

public CoinPage()
{
    InitializeComponent();
    this.add = new ToolbarItem{Text = "Add", Priority = 0, Order = ToolbarItemOrder.Primary};
    collectionView.SelectionChanged += CollectionView_SelectionChanged;
    add.Command = new Command((sender) =>
    {
        this.AddCommand();
    });
    MessagingCenter.Subscribe<User>(this, "CurrentUser", (sender) =>
    {
        user = sender; // -always null and can 't figure out why
    });
}

【问题讨论】:

  • 哎呀。直接将密码与这样的文本框匹配是非常不合适的。

标签: c# xamarin


【解决方案1】:

首先,你要Subscribe之前Send发消息

其次,要传递参数,请使用此语法

MessagingCenter.Send<MyClass, User>(this, "CurrentUser", user);

其中MyClass是发送消息的类型,User是参数的类型,this是对发送者的引用,CurrentUser是消息,user是参数

订阅

MessagingCenter.Subscribe<MyClass, User>(this, "CurrentUser", async (sender, arg) =>
{
  // do stuff
});

注意&lt;T1,T2&gt; 类型必须在SendSubscribe 之间匹配

【讨论】:

    【解决方案2】:

    你的问题可以参考以下代码:

    1.订阅消息

            MessagingCenter.Subscribe<object, object>(this, "CurrentUser", (sender, args) =>
            {
                User model = (User)args;
    
            });
    

    2.发布消息

            User user = new User { Name = "user1" ,age = 18};
    
            MessagingCenter.Send<object, object>(this, "CurrentUser", user);
    

    注意:

    在发布消息之前,请确保您已订阅消息。

    更多信息,请查看:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center

    【讨论】:

    • 嗨@NubianFlamaryu,我已经好几天没有收到你的消息了。如果有什么我可以在这里提供帮助的,请告诉我。
    猜你喜欢
    • 2012-11-06
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多