chiken nuget
chiken nuget

Reputation: 25

Is there a way to activate a Button that exists within another class?

I am using C# and Xamarin. I have two separate classes. One class is essentially the user interface and another class is acting as a custom built generic entry for users to input data and search for results by clicking a button.

Main UI Class:

Class MainPage
{
   public MainPage
   {
      Content = new StackLayout
      {
         Children =
         {
            new InputClass // This is my custom built user entry class
            {
            }.Invoke(ic => ic.Clicked += WhenButtonPressedMethod) // The problem is here, I can't figure out how to call the button within the input class to fire a clicked event.
         }
      }
   }
}

public async void WhenButtonPressedMethod (object sender, EventArgs e)
{
    // Supposed to do stuff when the button is pressed
}

InputClass:

public class InputClass : Grid
{
   public delegate void OnClickedHandler(object sender, EventArgs e);
   public event OnClickHandler Clicked;

   public InputClass
   {
      Children.Add(
      new Button {}
      .Invoke(button => button.Clicked += Button_Clicked)
      )
   }

   private void Button_Clicked(object sender, EventArgs e)
   {
       Clicked?.Invoke(this, e);
   }
}

The "InputClass" is a grid that holds a title text label, an entry and a button that a user can press to submit and search data. The button in this class is what I'm trying to actually access to invoke/cause a click event so that the method in the main UI class can be called. But, when I try to invoke a click event on the "InputClass" I can't access the button inside of it, I can only access "InputClass" itself which is just a grid with no useful event properties.

Any solutions or ideas?


If you are running into the same problem as mentioned here, follow the code on this page and read through the comments, it covers enough to be able to piece it together. My mistake was attaching Invokes to the wrong objects.

Upvotes: 2

Views: 160

Answers (1)

ToolmakerSteve
ToolmakerSteve

Reputation: 21321

Don't know why fluent Invoke didn't work correctly.
Add the event handlers this way:

public MainPage
{
    var ic = new InputClass();
    ic.Clicked += WhenButtonPressedMethod;
    Content = new StackLayout
    {
        Children = { ic }
    }
}

public InputClass
{
    var button = new Button;
    button.Clicked += Button_Clicked;
    Children.Add(button);
}

Upvotes: 1

Related Questions