区分按钮单击xamarin.forms

时间:2019-04-01 11:20:40

标签: xamarin.forms

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

我的按钮页面

  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();
        }

1 个答案:

答案 0 :(得分: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时,传递问题的键(然后在调用MyMessage时需要通过MessagingCenter.Send()传回该键

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