【问题标题】:Distinguish Button click xamarin.forms区分按钮单击 xamarin.forms
【发布时间】:2019-04-01 19:35:20
【问题描述】:

您好,我的 xamarin.forms 应用程序中有四个按钮。每次单击按钮都会在弹出窗口中打开一个列表视图。我试图在每次单击按钮时打开相同的弹出页面。我正在使用消息中心返回列表视图选定项返回按钮页面。我卡住的地方是如何区分弹出页面中的按钮点击?我应该使用标志还是其他东西?

我的按钮页面

  void Button1_Tapped(object sender, EventArgs e)
        {


            PopupNavigation.PushAsync(new AnswerPopup(tranzaction));

            MessagingCenter.Subscribe<MyMessage>(this, "AnsData", (value) =>
            {
                string receivedData = value.Myvalue;
                Answer1.Text = receivedData;
            });
        }

        void Button2_Tapped(object sender, EventArgs e)
        {

            PopupNavigation.PushAsync(new AnswerPopup(tranzaction));

            MessagingCenter.Subscribe<MyMessage>(this, "AnsData", (value) =>
            {
                string receivedData = value.Myvalue;
                Answer2.Text = receivedData;
            });
        }
        void Button3_Tapped(object sender, EventArgs e)
        {

            PopupNavigation.PushAsync(new AnswerPopup(tranzaction));

            MessagingCenter.Subscribe<MyMessage>(this, "AnsData", (value) =>
            {
                string receivedData = value.Myvalue;
                Answer3.Text = receivedData;
            });
        }

我的弹出页面

   private string selectedItem;     
        private void AnsList_Tapped(object sender, SelectedItemChangedEventArgs e)
        {
            var selectedCategory = e.SelectedItem as Answer;
            if (selectedCategory != null)
                selectedItem = selectedCategory.Text;
            MessagingCenter.Send(new MyMessage() { Myvalue = selectedItem.ToString() }, "AnsData");
            PopupNavigation.PopAsync();
        }

【问题讨论】:

  • 为什么不将每个按钮的唯一密钥发送到 AnswerPopup,然后让 AnswerPopup 通过 MessagingCenter 发回该密钥?
  • @Jason bro 你能解释一下吗?
  • @AndroDevil 您可以为所有这些按钮创建一个消息中心并在其中接收 buttonId 并使用 switch/case 来识别哪个按钮被点击。

标签: xamarin.forms


【解决方案1】:

首先,您不需要多次订阅,只需每页执行一次(通常在构造函数中)

其次,向MyMessage 添加一个属性,它会告诉您调用了哪个按钮

MessagingCenter.Subscribe<MyMessage>(this, "AnsData", (value) =>
        {
            string receivedData = value.Myvalue;

            switch (value.Question) {
              case "Q1":
                Answer1.Text = receivedData;
                break;
              case "Q2":
                Answer2.Text = receivedData;
                break;
              case "Q3":
                Answer3.Text = receivedData;
                break;
            }


        });

最后,在调用AnswerPopup 时,传递问题的密钥(然后在调用MessagingCenter.Send() 时需要通过MyMessage 传递回来

void Button1_Tapped(object sender, EventArgs e)
    {
        // use "Q2", "Q3", etc as appropriate
        PopupNavigation.PushAsync(new AnswerPopup(tranzaction, "Q1"));
    }

【讨论】:

  • 让我检查一下兄弟
  • 调用MessagingCenter.Send()时如何传递key?
  • 您已经在发送 MyMessage,只需向其中添加一个包含问题 ID 的属性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
  • 2019-02-23
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多